我有一个看起来像这样的函数:
async function sync(req, res, done){
await createRecords().then(async ()=> {
await Promise.all(
[
quantityReport(),
listings(),
productIdentifiers(),
productChildren()
])
}).then(async ()=>{
await saveAll()
} ).then(await createCSV);
}
module.exports = sync
我在开关中这样称呼它:
// const saveRecords = require('../scripts/saveRecords.js') <- for reference
await saveRecords;
我的问题是程序在 saveRecords 完成之前继续运行,我不知道为什么。
Promise.all 中的所有函数都是异步函数。
如果我直接在 saveRecords.js 中调用 sync() 它工作正常。
谢谢。
编辑
createCSV 在程序的其他位置也能正常工作。它像这样导入到这个文件中:
const {createCSV, uploadReports} = require('../scripts/createCSV.js')
//in createCSV.js
module.exports = createCSV;
答案 0 :(得分:0)
我会这样重构您的函数(顺便说一句,sync
听起来不是您函数的好名字,请写一些更明显的东西)。
async function sync(req, res, done){
try{
await createRecords()
const _res = await Promise.all([
quantityReport(),
listings(),
productIdentifiers(),
productChildren()
])
if(_res) {
await saveAll()
await createCSV()
}
return
}
catch(err){
throw new Error(err)
}
}
module.exports = sync
答案 1 :(得分:0)
正如我在评论中提到的,使用 async/await
和 then
from the Promise API(另见 fetch
)是一件奇怪的事情。使用其中之一。但关键问题是您没有调用同步函数await sync()
。
这是一个简单使用 async/await
的简单示例。
function mockCall(n) {
return new Promise((res, rej) => {
setTimeout(() => res(n), 1000);
});
}
async function sync() {
const first = await mockCall(1);
const twoToFive = await Promise.all([
mockCall(2),
mockCall(3),
mockCall(4),
mockCall(5)
]);
const six = await mockCall(6);
const seven = await mockCall(7);
console.log([ first, twoToFive, six, seven ]);
}
(async function main() {
await sync();
console.log('Let the processing resume!');
})();