首页 > 解决方案 > 如何使用异步等待将这个 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

标签: asynchronouses6-promise

解决方案


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));

推荐阅读