AngularJs $q 承诺与 async/await 兼容吗?

Bri*_*van 6 javascript angularjs typescript angular

我正在使用 TypeScript(版本分别为 9.07、1.5.11 和 3.7.5)开发 Angular/AngularJs 混合应用程序。我们所有的 HTTP 请求,甚至是由新的 Angular 组件发出的请求,都使用以纯 Javascript 实现的包装服务,该服务最初是与应用程序的“遗留”AngularJs 端一起开发的,其方法返回由 AngularJs $http 生成的 $q 承诺服务。由于该服务是纯 Javascript,因此输入返回值不是问题,因为 TypeScript 认为它们只是一个any,它非常乐意让我将其转换为IPromise<TReturnType>

async我的问题是这些承诺是否与 TypeScript 中的和关键字完全兼容await。使用简单的示例进行尝试似乎效果很好,但我担心一些极端情况的问题,这些问题只会在运行时使用带有非本机 Promise 的关键字时出现。

tri*_*cot 7

兼容性async不是问题,因为该关键字并不直接依赖于现有的 Promise 实例:它使相应的函数返回一个新创建的 EcmaScript Promise 对象。

如果async函数返回 thenable,则返回的本机 Promise 的解析将依赖于该 thenable。

您可以在这段代码中看到后一种效果:

async function test() {
    let thenable = { then: cb => cb(13) };
    return thenable;
}

let result = test();
console.log(result instanceof Promise);
result.then(console.log); // 13
Run Code Online (Sandbox Code Playgroud)

await关键字可以与返回 thenable 的表达式一起使用,因此在这种情况下也不需要具有 EcmaScript 兼容的 Promise:

async function test() {
    let thenable = { then: cb => cb(13) };
    let value = await thenable;
    console.log(value); // 13
}

test();
Run Code Online (Sandbox Code Playgroud)

所以总而言之,两个关键字都会识别 thenable 并按预期处理它。不要求 thenable 是原生 Promise 的实例。

当然,$q承诺是可以实现的,所以这很好。