对没有返回数据的函数的承诺

Promises for a function with no return data

本文关键字:函数 承诺 数据 返回      更新时间:2023-09-26

我正在尝试为节点解开一大堆基于回调的代码,似乎承诺是关键,因为我有很多异步数据库操作。 具体来说,我正在使用蓝鸟。

我被困在如何处理一个需要从数据库中检索数据并在this上设置某些值的函数上。 我试图实现的最终目标是这样的:

myobj.init().then(function() {
  return myobj.doStuff1();
}).then(function() {
  return myobj.doStuff2();
}).catch(function(err) {
  console.log("Bad things happened!", err);
});

特别是initdoStuff1doStuff2只需要在前一个完成时才运行,但它们都执行(多个)异步操作。

这就是我到目前为止对 init 的准备,但我不知道如何完成它:

Thing.prototype.init = function(force) {
  if (!this.isInitialized || force) {
    return datbase.query("...").then(function(results){
       // ... use results to configure this
    }).catch(function(err){
       console.log("Err 01");
       throw err;
    });
  } else {
    // ???
    // No data needs to be retrieved from the DB and no data needs to be returned per-se because it's all stored in properties of this.
    // But how do I return something that is compatible with the other return path?
  }
}

编辑:虽然链接的重复问题解释了类似的模式,但它并没有完全回答我的问题,因为它没有明确说明我可以毫无意义地解决承诺。

如果我

正确理解了你的问题,你可以这样做:

Thing.prototype.init = function(force) {
    if (!this.isInitialized || force) {
        return datbase.query("...").then(function(results){
           // ... use results to configure this
        }).catch(function(err){
           console.log("Err 01");
           reject(err);
           throw err;
        });
    } else {
        // ???
        // No data needs to be retrieved from the DB and no data needs to be returned per-se because it's all stored in properties of this.
        // But how do I return something that is compatible with the other return path?
       return Promise.resolve();
    }
  }
}

只需从您的 else 函数return Promise.resolve();即可。