如何在所有javascript ES6 Promise解决后运行 [英] How to run after all javascript ES6 Promises are resolved

查看:186
本文介绍了如何在所有javascript ES6 Promise解决后运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在替换一些使用jQuery Deferred对象的旧代码,我正在使用Bluebird / ES6 Promises进行重写。

I'm in the process of replacing some old code that used jQuery Deferred objects and I am rewriting using Bluebird/ES6 Promises.

如果我有多个异步调用,如何解决所有承诺后触发函数。

If I have multiple asynchronous calls, how can I trigger a function after all the promises are resolved.

使用jQuery Deferreds会是这样的:

Using jQuery Deferreds it would be something like this:

var requests = [...]; //some arbitrary data that is iterated to generate multiple ajax requests
var promises = [];
resuests.forEach(function(endpoint) {
    promises.push($.ajax({url: endpoint}));
});

$.when.apply($, promises).then(function() {
    alert('all promises complete!');
});

如何使用ES6 Promise语法重写此内容?

How do I rewrite this using ES6 Promise syntax?

推荐答案

由于这是标记的 bluebird 除了你已经获得的两个好的解决方案之外还有更蓝鸟的方式:

Since this is tagged bluebird in addition to the two good solutions you have already gotten here is a more "bluebird" way:

var requests = [...];

Promise.map(requests, $.get).then(function(results){
    alert('all promises complete!');
});

这可能很简单。

正如其他人所指出的那样,本机es6的方式是使用 Promise.all ,没有 Promise.resolve 或需要明确创建。本机承诺最干净的方式可能是:

As the others have pointed out, the native es6 way would be to use Promise.all, no Promise.resolve or explicit creation is needed. The cleanest way with native promises would probably be:

var requests = [...];
Promise.all(requests.map($.get)).then(function(results){

});

这篇关于如何在所有javascript ES6 Promise解决后运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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