简体   繁体   English

解决JSON数组中的所有Promise-JavaScript

[英]Resolve all promises in an array of json - javascript

I need to resolve all promises in an array of json, like this: 我需要解析json数组中的所有promise,如下所示:

let list = [
    { 
        id: 1,
        data: new Promise((resolve, reject) => {
            resolve('Cat')
        })
    },
    { 
        id: 2,
        data: new Promise((resolve, reject) => {
            resolve('Dog')
        })
    },
    { 
        id: 3,
        data: new Promise((resolve, reject) => {
            resolve('Mouse')
        })
    }
]

I use bluebird promises. 我使用蓝鸟承诺。 I used a for cycle to iterate all items, I would know if there was some way more elegant. 我使用了for循环来迭代所有项目,我想知道是否有某种更优雅的方法。

Expected result: 预期结果:

[ { data: 'Cat', id: 1 },
  { data: 'Dog', id: 2 },
  { data: 'Mouse', id: 3 } ]

This should work, Promise.all and array.map like the others, but the result is correct Promise.all和array.map应该可以正常工作,但是结果是正确的

 let list = [ { id: 1, data: new Promise((resolve, reject) => { resolve('Cat') }) }, { id: 2, data: new Promise((resolve, reject) => { resolve('Dog') }) }, { id: 3, data: new Promise((resolve, reject) => { resolve('Mouse') }) } ] Promise.all(list.map(item => item.data.then(data => ({...item, data})))) // that's it, that's what you want, the rest is for show now .then(results => { console.log(results); }); 

though, that's Native Promises ... you may want to look into Promise.props and/or Promise.map in bluebird for possibly simpler code yet 但是,这是本承诺...您可能想查看bluebird中的Promise.props和/或Promise.map,以获得可能更简单的代码

It could well be as simple as 它可能很简单

Promise.map(list, Promise.props)
.then(results => {
    console.log(results);
});

tested the above, and yes, it is that simple - the snippet below has my own version of Promise.map and Promise.props - and works (at least in this case) identically to bluebird 测试了上面的内容,是的,就是这么简单-下面的代码段具有我自己Promise.mapPromise.props版本-并且(至少在这种情况下)与bluebird一样工作

 Promise.props = obj => { const keys = Object.keys(obj); return Promise.all(Object.values(obj)).then(results => Object.assign({}, ...results.map((result, index) => ({[keys[index]]: result})))); }; Promise.map = (array, fn, thisArg) => Promise.all(Array.from(array, (...args) => fn.apply(thisArg, args))); let list = [ { id: 1, data: new Promise((resolve, reject) => { resolve('Cat') }) }, { id: 2, data: new Promise((resolve, reject) => { resolve('Dog') }) }, { id: 3, data: new Promise((resolve, reject) => { resolve('Mouse') }) } ] Promise.map(list, Promise.props) .then(results => { console.log(results); }); 

With Promise.all & some JavaScript. 带有Promise.all和一些JavaScript。

let list = [];
let promise = Promise.all(list.map(entry => entry.data));
promise.then((results) => {
  let final = results.map((result, index) => {
    return {data: result, id: list[index].id};
  });
  console.log(final);
});

Promise.all may be a good fit here: Promise.all可能很适合这里:

Promise.all(list.map(entry => entry.data)).then((resolved) => {
  // ...
});

You just need create an array of promises. 您只需要创建一个承诺数组即可。 you can do it with for or map 您可以使用formap

let promises = []

for(var i=0; i < list.length; i++)
  promises.push(list.data)

Promise.all(promises).then(resultList => { ... }).catch(err => { ... })

or simplest may with map 或最简单的可能与map

Promise.all(list.map(p => p.data)).then(resultList => { ... }).catch(err => { ... })

you can use lodash lib to minimize your code 您可以使用lodash lib最小化您的代码

const _ = require('lodash');

Promise.all(_.map(list, 'data')).then((data)=>{
    list.map((item,ind)=>{item.data = data[ind]});
    console.log(list);
})

Resolve Promise.all() to an actual usable array of JSON. 将Promise.all()解析为实际可用的JSON数组。

The problem: Promise.all() resolves to an array of resolved promises. 问题:Promise.all()解析为一系列已解决的Promise。 To see why this is an issue, copy and paste this into your console: 要查看为什么这是一个问题,请将其复制并粘贴到控制台中:

var promise1 = fetch('https://swapi.co/api/people/2'); // C-3PO
var promise2 = fetch('https://swapi.co/api/people/3'); // R2-D2

Promise.all([promise1, promise2])
    .then(res => console.log(res)); // resolved promises - trash...

See how there's no actual usable data in those resolved promises..? 看看那些解决的承诺中没有实际可用的数据吗? On the web, you need to call another promise to convert them to text or html or, most likely, beloved json. 在网络上,您需要打电话给另一个诺言,将它们转换为文本或html,或者很可能是最受欢迎的json。 But how can you do this efficiently? 但是如何有效地做到这一点?

Well, then solution to our Promise.all() issue is... more Promise.all()!!! 好吧,那么我们的Promise.all()问题的解决方案是...更多Promise.all()!!!

Example: 例:

var promise3 = fetch('https://swapi.co/api/people/1'); // Luke
var promise4 = fetch('https://swapi.co/api/people/4'); // Luke's daddy

Promise.all([promise3, promise4])
    .then(res => Promise.all([res[0].json(), res[1].json()]))
    .then(res => console.log(res)); // real data :)

Hope this helps someone! 希望这对某人有帮助! Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM