JS promises: is this promise equivalent to this async/await version?

…衆ロ難τιáo~ 提交于 2021-01-29 05:08:53

问题


If I have the following code

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

is this equivalent to

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?


回答1:


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

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

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));

And:

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

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);
});

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.



来源:https://stackoverflow.com/questions/61553862/js-promises-is-this-promise-equivalent-to-this-async-await-version

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!