首页 > 解决方案 > nodejs异步/承诺地狱

问题描述

我有以下功能:

const bulkPreprocess = (files) => {

let bulkOps = []

files.map(doc => {
    parse(doc).then(content => {
        const sent = sentiment(content)
        bulkOps.push(sentiment)
        bulkOps.push({anotherobject})
    })
})
  return bulkOps
}

由这样的 main 函数调用:

module.exports = (req, res) => {
    //parses post request with file uploads
    const form = new multiparty.Form()

    form.parse(req, (err, fields, allFiles) => {
        //called more than once
        const files = allFiles['files']
        let processed = bulkPreprocess(files).then(bulk => {
            console.log(bulk.length)  
            addToES(bulk)
        })
    })

    res.json({ success: true })
}

我的问题是,由于 bulkPreprocess 调用该parse函数(它是异步的),我不能让它等到所有文件都在addToES被调用之前被解析。parse 函数本身调用另一个异步函数(这就是我必须使其异步的原因)。

整个流程是这样的:

Main -> bulkPreprocess -> (Parse -> parseDoc) -> return value from bulkPre -> addToES

我尝试将所有函数更改为 async/await,我尝试map在 bulkPreprocess 的函数中返回一个 Promise。我试过回调。什么都没有解决。

有什么建议吗?

标签: javascriptnode.jspromiseasync-await

解决方案


Promise您需要在 async 之后从bulkPreprocesswhich resolves返回,parse因此您需要Promise.all等待所有parse调用完成

编辑:现在它在完成后将 对象推送到它bulkOpsresolve与之一起使用parse

const bulkPreprocess = (files) => {
    let bulkOps = [];
    return Promise.all(files.map(doc => {
        return parse(doc).then(content => {
            const sent = sentiment(content);
            bulkOps.push(sentiment);
            bulkOps.push({anotherobject});
        });
    })).then(() => bulkOps);
};

推荐阅读