对没有返回数据的函数的承诺
Promises for a function with no return data
我正在尝试为节点解开一大堆基于回调的代码,似乎承诺是关键,因为我有很多异步数据库操作。 具体来说,我正在使用蓝鸟。
我被困在如何处理一个需要从数据库中检索数据并在this
上设置某些值的函数上。 我试图实现的最终目标是这样的:
myobj.init().then(function() {
return myobj.doStuff1();
}).then(function() {
return myobj.doStuff2();
}).catch(function(err) {
console.log("Bad things happened!", err);
});
特别是init
,doStuff1
和doStuff2
只需要在前一个完成时才运行,但它们都执行(多个)异步操作。
这就是我到目前为止对 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();
即可。
相关文章:
- 从函数返回角度承诺
- 如何按照承诺使用mocha/chai/chai测试ES7异步函数
- 两个函数之间的角度承诺
- 当链接javascript承诺时,如何处理then()函数中的条件
- 角承诺的“then”函数的成功回调的词汇范围是什么?
- JQuery 承诺已经包含回调的函数
- 将同步函数包装到承诺中的最佳方法是什么?
- 在同一函数中解析承诺后返回承诺
- JavaScript中的延期/承诺概念是一个新的概念,还是函数式编程的传统部分
- “未捕获(在承诺中)”在获取“then”方法中调用拒绝函数时
- 使用 Promise 在另一个函数中调用带有 Bluebird 承诺库的函数
- 从承诺返回不返回函数会导致警告
- 尝试编写承诺时出错:承诺解析器对象不是函数
- 如何在恢复函数之前等待 JavaScript 承诺解析
- WinJS,从可能是异步的函数返回一个承诺,也可能不是异步的
- javascript承诺在循环中或如何逐个调用函数
- 按照承诺,通过与chai的函数调用验证已解析承诺的内容
- ES6承诺:如何用参数链接函数
- OfflineAudioContext.startRendering()基于承诺的函数在safari中不起作用
- NodeJS 多函数承诺