问题是你在另一个异步调用(async.each)中有一个异步调用(knex),cb(null, obj) 没有等待前一个异步任务完成,因此更早执行。此外,如果async.each 不是必需的,您可以去掉它并使用Promises。只需遍历 result.pass_fileData,将所有 knex 承诺存储在一个数组中,然后将 Promise.all 与该数组一起使用,就可以完成这项工作。
read_file: ['pass_fileData', function (result, cb) {
const obj = [];
const promises = [];
// asuming "result.pass_fileData" is an array
result.pass_fileData.forEach(function (item) {
const singlePromise = knex
.select('xxxxx')
.from('xxxx')
.innerJoin('xxxx', 'xxxx', 'xxx')
.where('xxxxx', '=', item)
.then(function (data) {
obj.push(data) // here I am pushing data to array
})
.catch(function (err) {
cb(err);
});
promises.push(singlePromise); // store all the promises in an array
});
Promises.all(promises).then(function() {
cb(null, obj);
});
}]
如果你可以使用async/await(为什么不呢?)你可以稍微修改一下代码
read_file: ['pass_fileData', async function (result, cb) {
const obj = [];
const promises = [];
// asuming "result.pass_fileData" is an array
result.pass_fileData.forEach(function (item) {
const singlePromise = knex
.select('xxxxx')
.from('xxxx')
.innerJoin('xxxx', 'xxxx', 'xxx')
.where('xxxxx', '=', item)
.then(function (data) {
obj.push(data) // here I am pushing data to array
})
.catch(function (err) {
cb(err);
});
promises.push(singlePromise); // store all the promises in an array
});
await Promises.all(promises);
cb(null, obj);
}]
注意async function (result, cb)...前面的async关键字和await Promises.all(promises);前面的await
希望对你有帮助