如何在异步函数中多次运行 Promise?

问题描述 投票:0回答:1

我正在学习 Promise 和 async wait,这里我想调用 addPost 函数并推送一个对象两次,然后我想循环该对象数组以查看结果,但在这段代码中,结果并不符合预期。在此,当该行点击 showDetails() 函数时,它仅显示 3 个对象,但应该有 4 个对象,我在这里缺少什么?

const posts = [{ title: 'Post 1' }, { title: 'Post 2' }];
var count = 3;

const diffFunction = async () => {
    const addPost = new Promise((resolve, reject) => {
        setTimeout(() => {
            posts.push({ title: `Post ${count}` });
            count++;
            resolve(count);
        }, 1000)
    })
    const deletePost = new Promise((res, rej) => {
        setTimeout(() => {
            const deltedPost = posts.pop();
            res(deltedPost);
        }, 2000)
    })

    const showDetails = () => {
        posts.forEach(element => {
            console.log(element.title);
        });
    }
    await addPost;
    await addPost;
    showDetails();
}
diffFunction();

javascript asynchronous async-await settimeout es6-promise
1个回答
0
投票

当您使用

new Promise()
创建 Promise 时,它会立即开始运行。您可以通过在控制台中运行类似
new Promise(() => { console.log("hello") })
的内容来测试这一点 - 您应该立即看到日志。

你可以通过定义一个返回新 Promise 的函数来实现你想要的行为。这样你的 Promise 才会在你调用该函数时运行,并且每个函数调用都会返回一个不同的 Promise。

const posts = [{ title: 'Post 1' }, { title: 'Post 2' }];
var count = 3;

const addPost = () => new Promise((resolve, reject) => {
    setTimeout(() => {
        posts.push({ title: `Post ${count}` });
        count++;
        resolve(count);
    }, 1000)
})

const deletePost = () => new Promise((res, rej) => {
    setTimeout(() => {
        const deltedPost = posts.pop();
        res(deltedPost);
    }, 2000)
})

const showDetails = () => {
    posts.forEach(element => {
        console.log(element.title);
    });
}

const diffFunction = async () => {
    await addPost();
    await addPost();
    showDetails();
}

diffFunction();

你可以看到我已经将

addPost
deletePost
更改为函数而不是承诺。

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