asynchronous - 如何使用异步等待将这个 promise.then 更改为 promise.all?
问题描述
const posts = [{
title: 'Post One',
body: 'This is Post 1'
},
{
title: 'Post Two',
body: 'This is Post 2'
},
{
title: 'Post Three',
body: 'This is Post 3'
}
]
我在这里创建帖子数组
function getPosts() {
setTimeout(() => {
let output = '';
posts.forEach((post) => {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
}, 1000);
}
首先,我通过 get Post 获取帖子。为了使它像我使用 setTimeoutFunction() 发出的 api 请求;
function CreatePost(post) {
return new Promise((resolve, reject) => {
setTimeout(() => {
posts.push(post);
const error = false;
if (!error) {
resolve();
} else {
reject('Error Something Went wrong')
}
}, 2000)
})
}
我用 CreatePost 创建了第四个帖子
function CreateAnotherPost(post) {
return new Promise((resolve, reject) => {
setTimeout(() => {
posts.push(post);
const error = false;
if (!error) {
resolve(console.log(posts));
} else {
reject('something went wrong')
}
}, 5000);
})
}
在这里,我创建了另一个等待时间很长的帖子
CreateAnotherPost({
title: 'Post Five',
body: 'This is post Five'
}).then(CreatePost({
title: 'Post Four',
body: 'This is post Four'
})).then(getPosts).catch(error => console.log(error));
我可以通过链接 .then 使其顺利运行。但我不知道如何使用promise.all
解决方案
Promise.all 接受一组 promise 并等待数组中的所有 promise 解决并返回已解决的 promoise,如果数组中的任何一个 promise 发生任何错误,它就会到达 catch 块
你可以试试这个方法
Promise.all([CreateAnotherPost({
title: 'Post Five',
body: 'This is post Five'
}),
CreatePost({
title: 'Post Four',
body: 'This is post Four'
})
]).then(getPosts).catch(error => console.log(error));
推荐阅读
- powershell - Powershell 按 MM/DD/YY、HH:MM AM/PM 排序
- arrays - 当某些键仅存在于几个数组中时,不确定使用 jq 过滤一组 json 数组的最有效方法 - //?
- java - 如何创建一个访问我的项目文件夹之外的文件的 Spring bean?
- javascript - 在Javascript控制台中输出姓氏的第一个字母以及大写字母的首字母?
- php - Laravel 根据变量是否为 null 执行 where 条件
- amazon-web-services - 如何在 CDK 中为基于 Lambda 的 APIGateway 提供自定义域名?
- c++ - 方法调用中带有字符串文字的 C++ const char*
- react-native - 无法在本机反应中更新状态值
- python - 如果没有,如何让 python 脚本执行另一个命令?
- google-apps-script - 如何使用脚本构建条件格式?