How to promisify?

寵の児 提交于 2020-01-06 19:47:08

问题


I have this sort of function:

someFunction.someMethod('param1', function(err, res1, res2) {
  req.method(res1, function(err) {
    if (!err) {
      console.log('Yes!');
    }
  });
})(req, res); // <-- This one's the problem!

Now when I try to promisify it:

var a = Promise.promisify(someFunction.someMethod);

a('param1').spread(function(res1, res2) {
  console.log('Yes!');
}).catch(function(err) {

});

it doesn't work anymore, because I cannot put the (req, res) at the end of it. How to achieve this?


回答1:


I would try this:

var a = Promise.promisify(function(arg, cb) {
    someFunction.someMethod(arg, cb)(req, res);
});

a('param1').spread(function(res1, res2) {
  console.log('Yes!');
}).catch(function(err) {

});

…and yes, it's ugly. This partial application might however be a sign that the function returned by someFunction.someMethod('param1', …) is supposed to be called multiple times; and your callback would be called as many times - where you cannot use promises any more.



来源:https://stackoverflow.com/questions/26254104/how-to-promisify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!