【问题标题】:Promise.resolve().then( vs Promise.resolve(Promise.resolve().then( 与 Promise.resolve(
【发布时间】:2022-02-06 23:03:36
【问题描述】:

我正在开发一些 Azure Functions - 我正在从 CosmosDB 中读取一些文档,并对这些文档执行一些操作。

我遇到过以下代码,但不是很明白。

  • 为什么要使用then(),难道不可以直接在resolve() 部分中删除它以及执行我想要的任何操作的代码吗?

所以:

const promises = documents.map(document =>
        Promise.resolve().then(async () => {
            // Do some stuff on the document
        })
);

return Promise.all(promises).then();

对比:

const promises = documents.map(document =>
        Promise.resolve(async () => {
            // Do some stuff on the document
        })
);

return Promise.all(promises).then();

【问题讨论】:

  • .then() 似乎也很可疑,也许这不是最好的学习代码。

标签: typescript promise azure-functions azure-cosmosdb


【解决方案1】:

实际上你不应该使用;而是去

const promises = documents.map(async document => {
    // Do some stuff on the document
});

你的第一个 sn-p 不必要地构造了一个立即解决的承诺,只是为了将一个函数链接到它。这会延迟计算以异步方式进行,这可能是故意完成的,但应该在评论中提及 - 为此只需使用 async document => { await void 0; … },避免混合两种 promise 样式。

你的第二个 sn-p 构造了一个用函数实现的承诺 - 这不是你想要的。

【讨论】:

    猜你喜欢
    • 2021-11-30
    • 2015-02-23
    • 2017-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    相关资源
    最近更新 更多