promisify如何运作,或者它的工作要求是什么? [英] How promisifyAll works, or what are the requirements for it work?

查看:160
本文介绍了promisify如何运作,或者它的工作要求是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在promise库中,bluebird具有函数promisifyAll或其他类似的库,声称将具有回调模式的异步函数转换为基于promise的ie。 resolve() reject(),或 done() ..那么它是如何工作的?

In a promise library bluebird have function promisifyAll or other similar libraries that claim to convert async functions with callback patterns into promise based ie. resolve(), reject(), or done()..So how does it work?

例如:

function myAsync1 (data, url, callBack) {...}

如果我把它放入

Promise.promisify(myAsycn1);

然后我的功能会像这样工作..

then will my function work like this..

myAsync1('{..}', 'http://..').then(function(){...});

这一直困扰着我。是否存在异步非承诺库或函数需要遵循的模式Bluebird promisifyAll将它们转换为基于promises的方法,或者有一些魔法可以转换它们。

This is have been bothering me. Is there a pattern that async non promise libs or function need to follow for Bluebird promisifyAll to convert them to promises based methods or there is some magic that converts them.

如果没有然后有什么要求以及如何使用现有的库如mongodb等。

If not then what are the requirements and how does it work with existing libraries like mongodb etc.

推荐答案


是有一个模式,异步非承诺库或功能需要遵循蓝鸟promisifyAll将它们转换为基于承诺的方法

Is there a pattern that async non promise libs or function need to follow for Bluebird promisifyAll to convert them to promises based methods

是的,有一种模式。它转换的函数必须将回调作为最后一个参数。此外,它必须将错误作为回调的第一个参数传递( null ,如果没有错误),返回值作为第二个参数。

Yes, there is a pattern. The functions it converts must expect a callback as their last argument. Additionally, it must pass an error as the first argument to the callback (null if no error) and the return value as the second argument.

由于优化,BlueBird promisify 函数非常难以理解,因此我将展示一种可以编写的简单方法:

The BlueBird promisify function is very difficult to follow because of optimizations, so I'll show a simple way it could be written:

function promisify(fn) {
  return function() {
    var that = this; // save context
    var args = slice.call(arguments); // turn into real array
    return new Promise(function(resolve, reject) {
      var callback = function(err, ret) { // here we assume the arguments to
                                          // the callback follow node.js
                                          // conventions
        if(err != undefined) {
          reject(err);
        } else {
          resolve(ret);
        }
      };
      fn.apply(that, args.concat([callback])); // Now assume that the last argument will
                                              // be used as a callback
    });
  };
}

现在我们可以实现 promisifyAll 循环遍历目标对象中的函数,并在每个函数上使用 promisify

Now we could implement promisifyAll by looping over the functions in the target object and using promisify on each one.

这篇关于promisify如何运作,或者它的工作要求是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆