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

时间:2016-02-27 03:14:26

标签: javascript node.js promise bluebird

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

我遇到了如何处理需要从数据库中检索数据并在this上设置某些值的函数。我想要完成的最终目标是:

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

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

这是我到目前为止的初始版本,但我不知道如何完成它:

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?
  }
}

编辑虽然链接的重复问题解释了类似的模式,但它并没有完全回答我的问题,因为它没有说明我可以解决任何事情的承诺。

1 个答案:

答案 0 :(得分:2)

如果我理解你的问题,你可以这样做:

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();
    }
  }
}

来自你的其他功能只需return Promise.resolve();

相关问题