简体   繁体   English

如何将闭包转化为承诺

[英]How to convert closure to promise

I am using closure inside for loop to save categories to categories table after article is saved. 保存article后,我在闭包内部使用for循环将类别保存到categories表。

article.save(function (err, newArticle) {
    if (err) throw err;
    console.log('article created ', newArticle._id);

    for (var i = 0; i < categories.length; i++) {

        (function (index) {
            var category_article = new category_article_model({
                "category": categories[index],
                "article_id": newArticle._id
            });

            category_article.save(function (err, new_category_article) {
                if (err) throw err;
            })
        }(i));
    }

    return res.status(res.statusCode).send(newArticle);
})

How do I convert the above to use promises? 如何将以上内容转换为使用诺言?

It seem's you're using MongoDB, which supports promises . 看来您使用的是MongoDB,它支持promises We can then use async/await (node >= 7.6), to make the code cleaner, and use Promise.all in order to wait until all categories are saved. 然后,我们可以使用async/await (节点> = 7.6)来使代码更整洁,并使用Promise.all来等待所有类别被保存。

app.post('/some/article', async(req, res) => {
                        // ^^^ notice async keyword
    const newArticle = await article.save();
    console.log('article created ', newArticle._id);

    // This will return an array of promises
    const categoryPromises = categories.map(category => {
        return new category_article_model({
            "category": category,
            "article_id": newArticle._id
        }).save(); // return a promise
    })

    // Promise.all takes an array of promises and waits
    // Until all promises are fulfilled
    await Promise.all(categoryPromises);

    // All categories are saved

    res.status(res.statusCode).send(newArticle);
});

As a side note, you should stop using var and start using let/const , doing so, you can remove the closure on your code, which isn't needed anyway. 附带说明一下,您应该停止使用var并开始使用let/const ,这样做可以删除代码上的闭包,无论如何都不需要。

 const categories = [1,2,3,4]; for (let i = 0; i < categories.length; i++) { // No need for closures setTimeout(() => console.log(`Using let: ${categories[i]}`)) } for (var j = 0; j < categories.length; j++) { // without closure it doesn't work setTimeout(() => console.log(`Using var: ${categories[j]}`)) } 

Check the following question: What's the difference between using "let" and "var" to declare a variable in JavaScript? 检查以下问题: 在JavaScript中使用“ let”和“ var”声明变量之间有什么区别?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM