JS诺言:此诺言是否等同于此异步/等待版本? [英] JS promises: is this promise equivalent to this async/await version?

查看:78
本文介绍了JS诺言:此诺言是否等同于此异步/等待版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下代码

new Promise(res => res(1))
.then(val => console.log(val))

等于

let val = await new Promise(res => res(1))
console.log(val)

我知道一个区别是我必须将第二个包装到一个异步函数中,否则它们等效吗?

I know one difference is that I have to wrap the second one in an async function, but otherwise are they equivalent?

推荐答案

因为您的诺言总是会解决(绝不会拒绝),所以它们是等效的.您也可以这样做:

Because your promise always resolves (never rejects), they are equivalent. You could also do:

Promise.resolve(1).then(val => console.log(val));

请记住,与 await 的主要区别(除了需要包装在 async 函数中)是诺言被拒绝时发生的事情.尽管您的示例很难解决,而不是拒绝,但让我们看一下实际错误处理(您应该始终知道)的样子:

Keep in mind that a major difference with await (besides it needs to be wrapped in an async function) is what happens when the promise rejects. Though your example is hard-wired to resolve, not reject, lets look at what they look like with actual error handling (which you should always have):

new Promise(res => res(1))
   .then(val => console.log(val))
   .catch(err => console.log(err));

并且:

try {
    let val = await new Promise(res => res(1));
    console.log(val);
} catch(e) {
    console.log(err);
}

或者,如果您没有try/catch,那么任何拒绝都会自动发送到由 async 函数自动返回的promise.错误的自动传播(同步异常和异步拒绝)在 async 函数中非常有用.

Or, if you didn't have the try/catch, then any rejects would automatically be sent to the promise that was automatically returned by the async function. This automatic propagation of errors (both synchronous exceptions and asynchronous rejections) is very useful in an async function.

当您有多个异步操作序列时,这一点将变得更加明显:

It becomes more apparent when you have multiple asynchronous operations in series:

const fsp = require('fs').promises;

async function someFunc() {
    let handle = await fsp.open("myFile.txt", "w");
    try {
         await handle.write(...);
         await handle.write(...);
    } finally {
        await handle.close().catch(err => console.log(err));
    }
}

someFunc().then(() => {
    console.log("all done");
}).catch(err => {
    console.log(err);
});

在这里, async 包装器从三个 await 语句中的任何一个捕获错误,并将它们全部自动返回给调用者. finally 语句捕获最后两个错误之一,以关闭文件句柄,但让该错误继续传播回调用者.

Here, the async wrapper catches errors form any of the three await statements and automatically returns them all to the caller. The finally statement catches either of the last two errors in order to close the file handle, but lets the error continue to propagate back to the caller.

这篇关于JS诺言:此诺言是否等同于此异步/等待版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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