微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JavaScript – Bluebird Promises加入行为

如果我使用Node.js执行以下代码
var Promise = require('bluebird');

Promise.join(
    function A() { console.log("A"); },function B() { console.log("B"); }
).done(
    function done() { console.log("done");}
);

控制台将记录

B
done

不过我会期待

A
B
done

要么

B
A
done

如果它在功能A中设置了一个断点,那么它永远不会达到.为什么它处理B但不是A?

解决方法

Promise.join承诺作为所有的论据,但是最后一个,这是一个功能.
Promise.join(Promise.delay(100),request("http://...com"),function(_,res){
       // 100 ms have passed and the request has returned.
});

你给它两个功能,所以它执行以下操作:

>对函数A(){…}做出承诺 – 基本上是对它做出承诺
>当完成(立即)执行最后一个参数时,函数B(){…}记录它.

查看文档:

Promise.join(Promise|Thenable|value promises...,Function handler) -> Promise

For coordinating multiple concurrent discrete promises. While .all() is good for handling a dynamically sized list of uniform promises,Promise.join is much easier (and more performant) to use when you have a fixed amount of discrete promises that you want to coordinate concurrently,for example:

var Promise = require("bluebird");

var join = Promise.join;

join(getPictures(),getComments(),getTweets(),

function(pictures,comments,tweets) {

console.log("in total: " + pictures.length + comments.length + tweets.length);

});

更新:

JSRishe想出了另一个聪明的方式来解决这种模式in this answer,它看起来像:

Promise.delay(100).return(request("http://...com").then(function(res){
    // 100 ms have passed and the request has returned 
});

这是因为在同一范围内调用函数之后,请求已经在延迟返回之前发生.

原文地址:https://www.jb51.cc/js/155603.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐