javascript - 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。我试过回调。什么都没有解决。
有什么建议吗?
解决方案
Promise
您需要在 async 之后从bulkPreprocess
which resolves返回,parse
因此您需要Promise.all
等待所有parse
调用完成
编辑:现在它在完成后将
对象推送到它bulkOps
并resolve
与之一起使用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);
};
推荐阅读
- bash - 使用 bash 从数组中提取匹配字符串的最佳方法
- r - 当用户输入的值发生变化时,在 Shiny Dashboard 中的 ggplot 中显示动态百分比和数量值
- javascript - 如何操纵孩子的渲染输出
- javascript - 主机断电后如何在脚本中使用wakeonlan?
- c# - Google OAuth ASP.NET MVC 示例代码的 CORS 问题
- powershell - 电源外壳。删除禁止字符
- c++ - 我想包装 std::array 来创建一个循环数组但是如何提供聚合初始化
- c# - 如何做多个不同的类来生成 XML?
- excel - 如何从 mongodb atlas 获取数据到 excel?
- android - 无法在颤动中更改/编辑启动画面和 xml 文件