使用Promise.all获得基于名称的结果的最佳方法 [英] Best es6 way to get name based results with Promise.all

查看:129
本文介绍了使用Promise.all获得基于名称的结果的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,Promise.All([])函数返回一个基于数字的索引数组,其中包含每个promise的结果。

By default the Promise.All([]) function returns a number based index array that contains the results of each promise.

var promises = [];
promises.push(myFuncAsync1()); //returns 1
promises.push(myFuncAsync1()); //returns 2
Promise.all(promises).then((results)=>{
    //results = [0,1]
}

使用Promise.all()返回指定结果索引的最佳方法是什么?

我尝试使用Map,但它以这种方式返回数组:
[key1,value1,key2,value2]

I tried with a Map, but it returns results in an array this way: [key1, value1, key2, value2]

更新:

我的问题似乎不清楚,这就是为什么我不喜欢基于订购的索引:


  1. 维护很糟糕:如果你在代码中添加一个promise,你可能需要重写整个结果函数,因为索引可能会有变化。

  2. 读取的内容很糟糕结果[42] (可以通过下面的jib答案修复)

  3. 在动态环境中不能真正使用

  1. it's crappy to maintain: if you add a promise in your code you may have to rewrite the whole results function because the index may have change.
  2. it's awful to read: results[42] (can be fixed with jib's answer below)
  3. Not really usable in a dynamic context:



var promises = [];
if(...)
    promises.push(...);
else{
    [...].forEach(... => { 
        if(...)
            promises.push(...);
        else
            [...].forEach(... => {
                promises.push(...);
            });
    });
}
Promise.all(promises).then((resultsArr)=>{
    /*Here i am basically fucked without clear named results 
        that dont rely on promises' ordering in the array */
});


推荐答案

这是件事吗?

var promises = [];
promises.push(myFuncAsync1().then(r => {name : "func1", result : r}));
promises.push(myFuncAsync1().then(r => {name : "func2", result : r}));
Promise.all(promises).then(results => {
    var lookup = results.reduce((prev, curr) => {
        prev[curr.name] = curr.result;
        return prev;
    }, {});
    var firstResult = lookup["func1"];
    var secondResult = lookup["func2"];
}

这篇关于使用Promise.all获得基于名称的结果的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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