栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

试图了解混杂如何与BlueBird一起工作

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

试图了解混杂如何与BlueBird一起工作

为了

promisifyAll()
正常工作,该函数必须是异步的,并且传递给该函数的最后一个参数必须是完成回调,而完成回调必须以其第一个参数作为错误参数,当没有错误且返回值时为false作为第二个参数(如果有值)。

您的功能不满足任何这些条件。


这是Bluebird文档

.promisifyAll()
的摘录:

假定目标方法符合node.js回调约定,即接受一个回调作为最后一个参数,并以错误作为第一个参数并以第二个参数的成功值调用该回调。如果node方法使用多个成功值调用其回调,则实现值将是它们的数组。

请记住,

.promisifyAll()
不能将同步操作转换为异步操作。所采取的是采取符合特定调用约定的异步操作,然后通过挂接回调并测试回调的参数以检测成功或失败并传播返回值,将其包装到Promise中。


如果您对Bluebird的操作方式感到好奇,可以在Github上查看其实际代码,尽管要进行精确的跟踪就很难了。

这里是一个简单的promisify函数版本,用于查看其功能(我建议将Bluebird用于所有其他功能,而不是使用它)。

// --------------------------------------------------------------// promisify(fn, obj)//// Pass an async function that takes as its last argument a callback// that conforms to the node.js callback calling convention function(err, result)// passing obj is optional.  If present the function passed in will be called// as obj.method()//// Returns: New function that when called will return a promise.// --------------------------------------------------------------function promisify(fn, obj) {    if (typeof fn !== "function") {        throw new Error("fn argument to promisify() must be function");    }    // obj is optional and may be undefined    // if present, it will be used as context to call fn as in obj.fn()    return function() {        // make copy of arguments object into a real array in a way that        // does not prevent interpreter optimizations        var args = new Array(arguments.length);        for (var i = 0; i < args.length; i++) { args[i] = arguments[i];        }        return new Promise(function(resolve, reject) { // add our callback function at the end of the args list var resultMany; args.push(function(err, result) {     if (err) {         reject(err);     } else {         // if 0 or 1 result, then just return it as a simple value         if (arguments.length <= 2) {  resolve(result);         } else {  // if more than one result came with the callback function,   // then put it into an array so we can resolve with a single value (the array of results)  // skip the first argument which is the err value  resultMany = new Array(arguments.length - 1);  for (var i = 0; i < arguments.length - 1; i++) {      resultMany[i] = arguments[i + 1];  }  resolve(resultMany);         }     } }); // call original function with our callback as last argument fn.apply(obj, args);        });    }}

这是此

promisify()
功能的工作演示:https :
//jsfiddle.net/jfriend00/m1265vos/



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/436603.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号