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})
}
有承诺的后端功能
function backendPromiseFunc(data) {
return new Promise((resolve, reject) => {
if (Number.isInteger(data)) {
resolve(`${data}`);
} else {
reject(`Invalid value: ${data}`);
}
});
}
然后异步请求的 Async 函数在数据数组末尾返回以停止循环
async function backendLoopCall() {
const numArray = [1, 2, 3, 4, 'hello'];
for (const data of numArray) {
console.log(`Processing: ${data}`);
try {
const result = await backendCall(data);
console.log(`Received result: ${result}`);
} catch (error) {
console.log(`Received error: ${error}`);
}
}
return;
}
最后调用调用函数
backendLoopCall();