提问人:Scott 提问时间:10/29/2023 更新时间:10/29/2023 访问量:38
如何等待javascript循环等待后端调用完成[duplicate]
How to wait for javascript loop to wait for backend call to finish [duplicate]
问:
Java 开发人员试图学习 javascript,但我无法为我的问题提出正确的解决方案。我正在尝试遍历一个对象数组,如果循环中的当前对象需要下载文件,则下载它,并将其设置为对象上的字段。在循环结束时,使用数组对象设置一个 reactjs 状态字段。我知道这个问题,但不知道解决它的最佳方法。我知道在所有循环/downloadAttachment 内容完成之前,setImprintInfo 被调用。谢谢,如果这是新手问题,很抱歉。
const setupImprintInfo = (imprints: Imprint[]) => {
imprints.forEach(imprint => {
if (imprint.shouldDownloadAttachment) {
downloadAttachment(imprint.id)
.then(blob=> {
imprint.attachment = blob
})
}
})
setImprintInfo({imprints: imprints})
}
答:
0赞
Junaid Raza
10/29/2023
#1
后端功能有承诺
function backendPromiseFunc(data) {
return new Promise((resolve, reject) => {
if (Number.isInteger(data)) {
resolve(`${data}`);
} else {
reject(`Invalid value: ${data}`);
}
});
}
然后异步函数在数据数组末尾返回异步请求以停止循环
async function backendLoopCall() {
const numArray = [1, 2, 3, 4, 'hello'];
for (const data of numArray) {
console.log(`Processing: ${data}`);
try {
const result = await backendPromiseFunc(data);
console.log(`Received result: ${result}`);
} catch (error) {
console.log(`Received error: ${error}`);
}
}
return;
}
最后调用调用函数
backendLoopCall();
确切地说,您的代码应该如下所示,并且必须在后端具有 promise 函数
const setupImprintInfo = async (imprints: Imprint[]) => {
for (const imprint of imprints) {
if (imprint.shouldDownloadAttachment) {
try {
const blob = await downloadAttachment(imprint.id);
imprint.attachment = blob;
} catch (error) {
console.error('Error downloading attachment', error);
}
}
}
setImprintInfo({ imprints: imprints });
}
希望对您有所帮助!
评论
.forEach
for ... in