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 
});

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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...