承诺在非节点式回调上使用Bluebird

Promisification with Bluebird on not node-style callbacks

本文关键字:Bluebird 回调 节点 承诺      更新时间:2023-09-26

我正试图在https://github.com/seishun/node-steam-trade,但此库正在使用非节点回调。

例如(Babel的ES6语法):

import bluebird from 'bluebird';
import SteamTrade from 'steam-trade';
bluebird.promisifyAll(SteamTrade.prototype);
let steamTrade = new SteamTrade();
// some kind of set sessionid/cookies
let result = await steamTrade.openAsync('my-steam-id');

最后一行并没有结束,因为传入回调的第一个参数是"数据",而不是错误(文档)。

如何配置bluebird来处理第一个参数中的数据?

您可能需要使用when.js(https://github.com/cujojs/when/blob/master/docs/api.md#whenlift)

或者你可以写自己的Promise包装。

steamTrade.openAsync = function(id){
  var promise = new bluebird( function(resolve, reject){
    steamTrade.open(id, function(data){ resolve(data); });
  });
  return promise;
};