我有以下函数:
const bulkPreprocess = (files) => {
let bulkOps = []
files.map(doc => {
parse(doc).then(content => {
const sent = sentiment(content)
bulkOps.push(sentiment)
bulkOps.push({anotherobject})
})
})
return bulkOps
}
由主函数调用,如下所示:
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
将所有函数更改为异步/等待,我尝试在 bulkPreprocess 中的 map
函数中返回一个承诺。我尝试了回调。什么都没有解决。
有什么建议吗?
您需要从异步parse
后解析的bulkPreprocess
返回Promise
,因此您需要等待所有parse
调用完成Promise.all
编辑:现在,它将对象推送到bulkOps
并在所有完成后parse
resolve
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);
};