【问题标题】:JS promises: is this promise equivalent to this async/await version?JS 承诺:这个承诺是否等同于这个 async/await 版本?
【发布时间】:2020-05-02 02:51:29
【问题描述】:

如果我有以下代码

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

这是否等同于

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

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

【问题讨论】:

  • 函数res是否返回一个Promise?
  • @stealththeninja - res 不会,res 解决了新的承诺......也许非 ES6 版本会帮助你理解 res 是什么 new Promise(function(res) { res(1);})
  • 是的,两个版本是等价的

标签: javascript asynchronous promise async-await es6-promise


【解决方案1】:

因为你的承诺总是解决(从不拒绝),所以它们是等价的。你也可以这样做:

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

请记住,与 await 的主要区别(除了它需要被包装在 async 函数中)是当 Promise 拒绝时会发生什么。尽管您的示例很难解决而不是拒绝,但让我们看看它们在实际错误处理中的样子(您应该始终拥有):

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 函数自动返回的承诺。这种错误的自动传播(同步异常和异步拒绝)在async 函数中非常有用。

当您有多个串行异步操作时,它会变得更加明显:

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 语句捕获最后两个错误中的任何一个以关闭文件句柄,但让错误继续传播回调用者。

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    相关资源
    最近更新 更多