如何在Bluebird中使用Promise包裝Node.js回調?這是我想出了,但想知道是否有更好的辦法:使用Bluebird在承諾中包裝Node.js回調
return new Promise(function(onFulfilled, onRejected) {
nodeCall(function(err, res) {
if (err) {
onRejected(err);
}
onFulfilled(res);
});
});
有一個更清潔的方式來做到這一點,如果只需要返回一個錯誤?
編輯 我試圖使用Promise.promisifyAll(),但結果沒有傳播到then子句。我的具體例子如下所示。我使用兩個庫:a)sequelize,它返回承諾,b)supertest(用於測試http請求),它使用節點樣式回調。以下是不使用promisifyAll的代碼。它調用sequelize來初始化數據庫,然後發出HTTP請求來創建訂單。 Bosth的console.log報表打印正確:
var request = require('supertest');
describe('Test', function() {
before(function(done) {
// Sync the database
sequelize.sync(
).then(function() {
console.log('Create an order');
request(app)
.post('/orders')
.send({
customer: 'John Smith'
})
.end(function(err, res) {
console.log('order:', res.body);
done();
});
});
});
...
});
現在我嘗試使用promisifyAll,這樣我可以鏈則呼籲:
var request = require('supertest');
Promise.promisifyAll(request.prototype);
describe('Test', function() {
before(function(done) {
// Sync the database
sequelize.sync(
).then(function() {
console.log('Create an order');
request(app)
.post('/orders')
.send({
customer: 'John Smith'
})
.end();
}).then(function(res) {
console.log('order:', res.body);
done();
});
});
...
});
當我到了第二的console.log的res參數未定義。
Create an order
Possibly unhandled TypeError: Cannot read property 'body' of undefined
我在做什麼錯了?
可能重複[?如何將現有的回調API來承諾(http://stackoverflow.com/questions/22519784/how-do-i-convert- an-existing-callback-api-promises) – Bergi
請參閱我編輯的答案(評論通知) – Esailija
您已將'.then'鏈接到不返回任何內容的'.then'。您的原始問題是重複的,您的編輯僅僅是正確使用'.then'處理程序。 –