Bluebird で Promise を使用して Node.js コールバックをラップするにはどうすればよいですか? これは私が思いついたものですが、より良い方法があるかどうかを知りたいと思っていました:
return new Promise(function(onFulfilled, onRejected) {
nodeCall(function(err, res) {
if (err) {
onRejected(err);
}
onFulfilled(res);
});
});
エラーのみを返す必要がある場合、これを行うためのよりクリーンな方法はありますか?
編集 Promise.promisifyAll() を使用しようとしましたが、結果が then 句に反映されていません。私の具体例を以下に示します。私は 2 つのライブラリを使用しています: a) promise を返す Sequelize、b) node スタイルのコールバックを使用する supertest (http 要求のテストに使用)。promisifyAll を使用しないコードを次に示します。Sequelize を呼び出してデータベースを初期化し、HTTP 要求を作成して注文を作成します。両方の 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();
});
});
...
});
2 番目の console.log に到達すると、res 引数が定義されていません。
Create an order
Possibly unhandled TypeError: Cannot read property 'body' of undefined
私は何を間違っていますか?