【问题标题】:How can I use 'finally' within a 'Promise' clause in NodeJS?如何在 NodeJS 的“Promise”子句中使用“finally”?
【发布时间】:2018-04-07 10:31:31
【问题描述】:

我想要这样的东西:

let promises = [];
for (let i = 0; i < some_length; i++) {
    let output = '';
    promises.push(some_func(i)
        .then((result) => {
            output = result;
        })
        .catch((error) => {
            output = error.message;
        })
        .finally(() => {
            console.log(output);
        })
    );
}
return Promise.all(promises);

但我收到运行时错误.then(...).catch(...).finally is not a function

我该如何解决这个问题?

【问题讨论】:

  • finally 尚不在标准中,因此 Node.js 不支持。不过你可以使用this polyfill
  • @Bergi:好的,换句话说,切换到(更新的)async/await 范式,无论如何我们都计划在某个时候这样做,但希望会有在Pomise 范式中是一个类似的机制。谢谢!!!
  • @goodvibration async/await 仍在使用 Promise 范式,只是语法糖更多。
  • 顺便说一句,对于您问题中的示例,我建议您简化为some_func(i).catch(err =&gt; err.message).then(console.log)(这可能比任何finally+await 更好,因为您总是需要output变量)

标签: node.js promise try-catch-finally


【解决方案1】:

实际上,我认为您的some-func 函数不返回Promise,返回JavaScript Promisees 和thencatchfinally 是有意义的,所以我认为您必须声明some_func 函数作为 new 实例的 Promise 对象,见以下代码:

let promises = [];
for (let i = 0; i < some_length; i++) {
    let output = '';
    let some_func = (i) => {
       return new Promise(function(resolve, reject) {
            setTimeout(resolve(`success: ${i}`), 100, 'foo');
       });
    }
    promises.push(some_func(i)
        .then((result) => {
            output = result;
        })
        .catch((error) => {
            output = error.message;
        })
        .finally(() => {
            console.log(output);
        })
    );
}
return Promise.all(promises);

也许这段代码还有其他错误,我不知道,因为我没有测试它,但毫无疑问,你的错误就像我在上面的句子中所说的那样。

【讨论】:

    【解决方案2】:

    Node 10 终于添加了对它的支持。使用节点 10.7.0 测试。

    Promise.resolve().finally(() => {
        console.log("It finally works!")
    })
    

    终于成功了!

    (顺便说一句,Chrome 和 Firefox 也支持它。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-29
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 2023-01-27
      相关资源
      最近更新 更多