如何更改此promise.then以异步等待的方式来保证promise。?

问题描述 投票:1回答:3
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'
    }
]

我在这里创建posts数组

function getPosts() {
    setTimeout(() => {
        let output = '';
        posts.forEach((post) => {
            output += `<li>${post.title}</li>`;
        });
        document.body.innerHTML = output;
    }, 1000);
}

[首先,我通过获取帖子获得帖子。为了使其类似于我使用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));

我可以通过链接使其平稳运行。然后。但我不知道如何使用promise.all

const posts = [{title:'Post One',body:'This is Post 1'},{title:'Post Two',body:'This is Post 2'},{title:'Post Three',正文:...

asynchronous es6-promise
3个回答
1
投票

Promise.all接受一个promise数组,并等待该数组中的所有promise解析并返回已解决的promoise,如果数组中任何promise中的任何错误发生,它都会到达catch块


1
投票

Promise.all


1
投票

当您有多个承诺并且要并行运行那些异步操作时,请使用Promise.all()。要使用它,您只需传递Promise.all()一个promise数组:

© www.soinside.com 2019 - 2024. All rights reserved.