Javascript异步在循环内获取请求 [英] Javascript async get request inside loop
问题描述
我有一个看起来像这样的对象数组:
I have an array of objects that looks like this:
[ { firstName: 'Mike', lastName: 'Jones' },
{ firstName: 'Joe', lastName: 'Smith' },
{ firstName: 'Bob', lastName: 'Johnson' } ]
我需要将该数组传递给一个函数,该函数将向每个对象添加一个"middleName"字段,并为MiddleName赋一个值.该函数通过在Node中发出异步http.get请求来获取中间名.问题就在这里.无论如何尝试,我都无法完成这项工作.
I need to pass that array to a function that's going to add a "middleName" field to each object, and a value for middleName. The function gets the middle name by making an asynchronous http.get request in Node. And therein lies the problem. I can't make this work no matter how I try.
以前有人建议过这样的循环:
Previously someone suggested a loop like this:
array.forEach(function (obj) {
GetMiddleName(obj, function (person) {
obj.MiddleName = person;
});
});
但是,由于在GetMiddleName函数中调用get的异步特性,因此无法正常工作.谁能给我看一个简短,简单的函数来满足我的需求?
But that doesn't work due to the async nature of the get being called in the GetMiddleName function. Can anyone show me a short, simple function that will do what I need?
推荐答案
制作一个Promises数组,在该数组上调用 Promise.all
,然后在每个数组中插入中间名:
Make an array of Promises, call Promise.all
on that array, and then insert the middle name to each:
const getMiddleNameProm = obj => new Promise((resolve) => {
GetMiddleName(obj, resolve);
});
Promise.all(arr.map(getMiddleNameProm))
.then((middleNames) => {
for (let i = 0; i < middleNames.length; i++) {
arr[i].MiddleName = middleNames[i];
}
// do stuff with populated arr here
});
});
这篇关于Javascript异步在循环内获取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!