[英]Typescript async/await and angular $q service
New TypeScript async/await feature uses ES6 promises. 新的TypeScript异步/等待功能使用ES6承诺。 AngularJS uses
$q
service promises with slightly different interface. AngularJS使用
$q
服务承诺,界面略有不同。
Is there any way to use TypeScript async/await feature with $q
service promises? 有没有办法在
$q
服务承诺中使用TypeScript async / await功能?
You can make it work like this: 你可以让它像这样工作:
angular.module('your app')
.run(['$window', '$q', function($window, $q) {
$window.Promise = $q;
}]);
I do not think you will be able to use them directly. 我认为你不能直接使用它们。 But it should be quite easy to convert q promise into a++ promise, something like this:
但是将q promise转换为++ promise应该很容易,如下所示:
function Convert<T>(qPromise): Promise<T>
{
return new Promise<T>((resolve, reject) =>
{
qPromise.then((result: T) => resolve(result), (e) => reject(e));
});
};
Finally I used the following workaround: 最后我使用了以下解决方法:
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 generates __awaiter
function in every file where await
operator is used. Comliper for Typescript 1.8在每个使用
await
运算符的文件中生成__awaiter
函数。 I replace it with implementation which passes custom Promise
constructor which initiates digest cycle after every resolve
and reject
call. 我将它替换为通过自定义
Promise
构造函数的实现,该构造函数在每次resolve
和reject
调用后启动摘要循环。 Here is usage example: https://github.com/llRandom/ts-awaiter 以下是用法示例: https : //github.com/llRandom/ts-awaiter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.