我有一个
bulkSave
函数,我想重复调用 API。
后续 API 取决于之前的 API。
我的问题是,如果
createProjectPeopleOrganization
成功返回,而 createProjectPeople
返回错误,我将如何以用户知道 createProjectPeopleOrganization
成功而 createProjectPeople
返回错误的方式返回它?另外,这里使用 for of
合适吗?
const peopleAndOrganizationIds = [
{
personId: '123',
organizationId: '54435'
},
{
personId: '435',
organizationId: '5435635'
}
]
代码
export const bulkSave = async ({ data }) => {
const { projectId, peopleAndOrganizationIds } = data;
try {
for (const item of peopleAndOrganizationIds) {
const { personId, organizationId } = item;
const { person } = await getPerson({ personId });
if (!person) {
return new Response(null, {
status: 400,
statusText: "No person found",
});
}
const organizationContext = person.organization;
const { created_project_people_organization } =
await createProjectPeopleOrganization({
object: {
project_id: projectId,
global_directory_organization_id: organizationId,
context: organizationContext,
},
});
const { created_project_people } = await createProjectPeople({
object: {
project_id: projectId,
global_directory_people_id: personId,
project_people_organization_id: created_project_people_organization?.id,
},
});
}
return new Response(null, {
status: 200,
statusText: "Success",
});
} catch (error) {
return new Response(null, {
status: 500,
statusText: "Internal Server Error",
});
}
};
您应该使用
Promise.allSettled
来代替。你可以像这样实现。
Promise.allSettled([
createProjectPeopleOrganization({
object: {
project_id: projectId,
global_directory_organization_id: organizationId,
context: organizationContext,
},
}),
createProjectPeople({
object: {
project_id: projectId,
global_directory_people_id: personId,
project_people_organization_id: created_project_people_organization?.id,
},
});,
]).then((results) => {
// results is an array of:
// {status: "fulfilled", value: 1}
// {status: "rejected", reason: Error}
});
然后您可以继续处理您认为合适的各个结果。