Typescript async/await and angular $q service

后端 未结 3 593
孤城傲影
孤城傲影 2021-02-05 08:51

New TypeScript async/await feature uses ES6 promises. AngularJS uses $q service promises with slightly different interface.

Is there any way to use TypeScri

3条回答
  •  不知归路
    2021-02-05 09:07

    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((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. I replace it with implementation which passes custom Promise constructor which initiates digest cycle after every resolve and reject call. Here is usage example: https://github.com/llRandom/ts-awaiter

提交回复
热议问题