新的TypeScript异步/等待功能使用ES6承诺。 AngularJS使用$q
服务承诺,界面略有不同。
有没有办法在$q
服务承诺中使用TypeScript async / await功能?
答案 0 :(得分:18)
你可以让它像这样工作:
angular.module('your app')
.run(['$window', '$q', function($window, $q) {
$window.Promise = $q;
}]);
答案 1 :(得分:4)
我认为你不能直接使用它们。但是将q promise转换为++ promise应该很容易,例如:
function Convert<T>(qPromise): Promise<T>
{
return new Promise<T>((resolve, reject) =>
{
qPromise.then((result: T) => resolve(result), (e) => reject(e));
});
};
答案 2 :(得分:1)
最后我使用了以下解决方法:
declare var __awaiter: Function;
(window as any).__awaiter = __awaiter; // set global __awaiter to avoid declaring default __awaiter in other files
async () => { } // dummy async function to generate __awaiter code for current file
angular.module('ts-awaiter', []).run(['$timeout', ($timeout: ng.ITimeoutService) => {
function wrap(func: Function) {
return function () {
func.apply(this, arguments);
$timeout(() => { }); // run angular digest
};
}
var oldAwaiter = __awaiter;
(window as any).__awaiter = (thisArg: any, _arguments: any, P: Function, generator: any) => {
P = function (executor: Function) {
return new Promise<any>((resolve, reject) => {
resolve = wrap(resolve);
reject = wrap(reject);
executor(resolve, reject);
});
};
return oldAwaiter(thisArg, _arguments, P, generator);
};
}]);
Comliper for Typescript 1.8在使用__awaiter
运算符的每个文件中生成await
函数。我将其替换为传递自定义Promise
构造函数的实现,该构造函数在每次resolve
和reject
调用后启动摘要周期。以下是用法示例:https://github.com/llRandom/ts-awaiter