8

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

私は何を間違っていますか?

4

1 に答える 1

8

あなたは約束を返すバージョンを呼び出しておらず、それも返していません。

これを試して:

   // Add a return statement so the promise is chained
   return request(app)
            .post('/orders')
            .send({
                customer: 'John Smith'
            })
            // Call the promise returning version of .end()
            .endAsync(); 
于 2014-03-31T12:59:56.903 に答える