使用异步函数返回Promise [英] Returning Promise with an async function

查看:105
本文介绍了使用异步函数返回Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下两个实现(在ES6/NodeJS中)

Given the following two implementations (in ES6 / NodeJS)

async TestFunc() {
    return new Promise((resolve,reject) => {
        ...
    });
}

TestFunc() {
    return new Promise((resolve,reject) => {
        ...
    });
}

如果我像这样调用这两个函数,在行为上是否有区别?

Is there any difference in behavior if I were to call either of these functions like so?

await TestFunc();

我假设第一个(异步)实现将返回一个promise,而我们将等待它返回另一个promise,而后者(同步)实现将返回promise,然后将等待它.但是,它们都按预期工作,这让我有些困惑.

I would assume that the first (async) implementation would return a promise, and we would be awaiting that to return another promise, whereas the latter (synchronous) implementation would return the promise, which then would get awaited. However, they both work as expected, leaving me a bit confused.

推荐答案

异步函数返回的promise将由在函数体中执行的 return 语句返回的值(或已解析的)解决如果执行完最后一行功能代码后返回,则返回 undefined .

An async function returns a promise that will be resolved by the value returned by a return statement executed in the function body (or resolved with undefined if returning after executing the last line of function code).

用承诺解决承诺,使解决的承诺承担解决状态的价值,以及解决承诺的价值.

Resolving a promise with a promise makes the resolved promise take on the settled state and value of the resolving promise when and if it becomes settled.

因此,始终在第一次调用时从异步函数主体中同步地返回承诺 P 会立即将通过调用异步函数返回的承诺的结果链接到 P 的结果.对于同步返回的Promise,这是不必要的步骤,并且该函数的 async 声明不是必需的.

So always synchronously returning a promise P from an async function body on first call immediately links the outcome of the promise returned by calling the async function to the outcome of P. This is an unnecessary step for a synchronously returned promise and the async declaration of the function is not necessary.

如果 TestFunc 是异步函数,则

await TestFunc();

await 运算符的操作数是通过调用 async 函数生成的promise.此承诺将通过函数体代码中返回的承诺来解决.

the operand of the await operator is the promise generated by calling the async function. This promise will be settled by a promise returned in function body code.

如果 TestFunc 不是异步函数,则

await TestFunc();

await 运算符的操作数是由 TestFunc 构造并返回的promise.有效的区别是 TestFunc 不能在内部使用 await 运算符而不将其更改回异步函数.

the operand of the await operator is the promise constructed and returned by the TestFunc. The effective difference is that TestFunc can't internally use the await operator without changing it back to an async function.

这篇关于使用异步函数返回Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆