让方法在 node.js 中返回带有蓝鸟的虚拟承诺的正确方法是什么

What is the correct way to have a method return a dummy promise with Bluebird in node.js

本文关键字:方法 虚拟 承诺 是什么 蓝鸟 node js 返回      更新时间:2023-09-26

所以,我有一个函数,上面有这样的承诺链:

Myclass.Prototype.initAsync = function() {
  someFunctionAsync(params).bind(this)
    .then(function(data) {
      processData(data);
      return someOtherFunctionAsync(params).bind(this);
    })
    .then(function(data) {
      processData(data);
      return yetAnotherFunctionAsync(params).bind(this);
    })
    .finally(function(data) {
      processData(data);
    });
 }

它有效,但我希望这个函数本身能够在承诺链中。通常,我只是去掉最后的"最后",但我不希望调用者负责调用 processData。我希望能够像这样调用这个函数:

setupFunctionAsync(params).bind(this)
  .then(function(data) {
    processSetup();
    return initAsync();
  })
  .finally(function(data) {
    runProgram();
  });

在 initAsync 的"最终"中,正确的做法是什么?我是否想使用 Promise.new 创建一个新的空承诺并返回它?还是我想将 Promise.method 与空方法一起使用?还是有更好的方法?

现在我正在执行以下操作,但我想知道这是否是最好的选择:

return someFunctionAsync(params).bind(this)
   .then(function(data) {
...
   .then(function(data) {
     processData(data);
     return new Promise(function(resolve, reject) { resolve(); });
   });

最新更新:

在阅读了一些答案之后,这会起作用吗?

Myclass.Prototype.initAsync = function() {
  return someFunctionAsync(params).bind(this)
    .then(function(data) {
      processData(data);
      return someOtherFunctionAsync(params).bind(this);
    })
    .then(function(data) {
      processData(data);
      return yetAnotherFunctionAsync(params).bind(this);
    })
    .then(function(data) {
      processData(data);
    });
  }

它被称为:

this.initAsync()
  .then(function() {
    runProgram();
  });

请注意,我在 initAsync 的最后一个然后中没有"返回"。可以吗?

我认为你误解了finally.在任何情况下都会调用传递给 finally 的函数,这意味着当承诺被解析和被拒绝时。 finally还返回另一个承诺(具有前一个承诺的值),因此链接没有问题。

看起来很像你应该使用then,你只使用finally因为它似乎很适合这个过程的最后一步。您可以在此处使用then

无论如何,由于finally已经返回了一个承诺,你可以在函数的开头添加一个return。你不需要"虚拟承诺"。

在最后一个then传递的函数中没有 return 语句不是问题。这只是意味着没有值传递给then之后链接的下一个承诺。但是,无论如何都会调用它。您添加到问题中的代码看起来很好。