我有很多问题。每个问题都有一些答案,这些答案需要上传一些文件。一切顺利,而不是API调用没有等待Promise.all完成的事实。
以下是步骤:
导出功能sendReview(taskId,companyId,问题,导航){ 返回异步(发送)=> {
dispatch(actions.sendReview.pending());
try {
let user = await getUser();
user = JSON.parse(user);
questions.map(async(question) => {
if(question.type === 'image'){
let images = question.answer;
if(images.length > 0){
const results = images.map(async (image) => {
return await imageApi.upload(image).then(res => {
return res.url;
});
});
question.answer = await Promise.all(results).then((completed) => {
return completed
});
}
}
});
const data = await tasksApi.sendReview({
task_id: taskId,
company_id: companyId,
user_id: user.id,
questions: JSON.stringify(questions)
});
if(data.status === 201){
markAsCompleted(taskId);
navigation.navigate('MyTasks');
dispatch(actions.sendReview.success({}));
}else{
dispatch(actions.sendReview.error());
}
} catch (err) {
dispatch(actions.sendReview.error(err));
}
}; }
这里是使用的功能。
如何确保.map()中的所有项目均已准备就绪,并且在进行API调用之后?
答案 0 :(得分:1)
使用Promise.all
等待数组中的诺言
Promise.all(questions.map(...))
答案 1 :(得分:0)
为您提供我一段时间前编写的代码的示例:
await Promise.all((await readdir(repoPath, "utf8")).map(async file => {
if (!/\.mjs$/.test(file)) return;
const filePath = `${repoPath}/${file}`;
log(`importing "${file}"`);
const module = await import(filePath);
const meta = {
repository,
file,
filePath,
description: module.description || {}
};
module.default((...args) => createModule(meta, ...args));
}));
如果您有异步映射处理程序,则需要记住,生成的映射的内容包含promise。
Promise.all()
将帮助您。
因此,您需要做的就是更改:
questions.map(async(question) => {
if(question.type === 'image'){
let images = question.answer;
if(images.length > 0){
const results = images.map(async (image) => {
return await imageApi.upload(image).then(res => {
return res.url;
});
});
question.answer = await Promise.all(results).then((completed) => {
return completed
});
}
}
});
如下:
await Promise.all(questions.map(async(question) => {
if(question.type === 'image'){
let images = question.answer;
if(images.length > 0){
const results = await Promise.all(images.map(async (image) => {
return await imageApi.upload(image).then(res => {
return res.url;
});
}));
question.answer = results.then((completed) => {
return completed
});
}
}
}));