我有3条记录。为了更新每条记录,我需要获取上一条记录的值。问题是方法是异步记录时,记录三在记录二完成之前开始更新并获取null值。我该如何处理?
const resolvePersons = async (persons) => {
return Promise.all(persons.map(async (person) => {
const data = await getSomePersonData(person);
const value = await getValue(persons); // first person value is statically set
return { data, value };
}));
};
function getSomePersonData(person) {
return new Promise((resolve, reject) => setTimeout(() => resolve({data: someData}), 100);
}
function getValue(persons) {
return new Promise((resolve, reject) => setTimeout(() => resolve(persons[index - 1].value), 100);
}
答案 0 :(得分:2)
如果您不希望迭代同时运行,请不要使用Promise.all
和map
。只需编写一个await
有问题的普通循环即可:
async function resolvePersons(persons) {
const result = [];
for (const [i, person] of persons.entries()) {
const data = await getSomePersonData(person);
const prevValue = i == 0 ? null : result[i-1].value;
const value = await getValue(prevValue);
result.push({ data, value });
}
return result;
}