解决 json - javascript 数组中的所有承诺

Resolve all promises in an array of json - javascript

我需要解决 json 数组中的所有承诺,如下所示:

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')
        })
    }
]

我使用 bluebird 承诺。 我用for循环遍历所有项目,我想知道是否有更优雅的方法。

预期结果:

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

Promise.all 可能很适合这里:

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

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

您只需要创建一个承诺数组。你可以用 formap

let promises = []

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

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

或最简单的 map

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

您可以使用 lodash 库来最小化您的代码

const _ = require('lodash');

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

这应该有效,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);
});

尽管如此,那是 Native Promises ...您可能想查看 Promise.props and/or Promise.map in bluebird 以获得可能更简单的代码

它可以像

一样简单
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.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);
});

将Promise.all()解析为实际可用的JSON数组。

问题:Promise.all() 解析为一组已解析的承诺。要查看为什么这是一个问题,请将其复制并粘贴到您的控制台中:

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

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

看看那些已解决的承诺中怎么没有实际可用的数据..?在 Web 上,您需要调用另一个 promise 将它们转换为文本或 html 或者,很可能是 beloved json。但是如何才能有效地做到这一点呢?

那么,我们 Promise.all() 问题的解决方案是……更多 Promise.all()!!!

示例:

var promise3 = fetch('https://swapi.dev/api/people/1'); // Luke
var promise4 = fetch('https://swapi.dev/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 :)

希望这对某人有所帮助!谢谢!