await调用异步函数未等待执行完成就提前继续运行问题求助
问题排查及修复方案
1. 函数未正确调用
你导入的saveRecords是sync函数本身,当前调用写法await saveRecords没有执行函数,只是等待了函数对象本身,自然不会等待内部逻辑执行。
修复:调用时添加括号执行函数
await saveRecords();
2. sync函数内部then回调写法错误
你在最后一个then中直接写了await createCSV,会在代码执行到这一行时就立即触发createCSV执行,而不是等待前面的Promise链完成后再执行,导致逻辑顺序错乱。
修复:将then的参数改为函数引用
// 原有错误写法 ).then(await createCSV); // 修改为 ).then(() => createCSV()); // 或直接传入函数引用(如果createCSV不需要接收额外参数) ).then(createCSV);
3. createCSV导入方式错误
你的createCSV.js是默认导出module.exports = createCSV,但你使用了解构语法导入,会导致拿到的createCSV为undefined,执行时报错中断逻辑。
修复:修改导入语句为默认导入语法
// 原有错误写法 const {createCSV, uploadReports} = require('../scripts/createCSV.js') // 修改为 const createCSV = require('../scripts/createCSV.js') // 如果需要同时导入uploadReports,需要修改createCSV.js的导出逻辑为: // module.exports = {createCSV, uploadReports}
额外优化建议
你当前的代码混用了async/await和then链式调用,可读性较差,可统一用async/await改写,逻辑更清晰:
async function sync(req, res, done){ await createRecords(); await Promise.all([ quantityReport(), listings(), productIdentifiers(), productChildren() ]); await saveAll(); await createCSV(); } module.exports = sync
内容的提问来源于stack exchange,提问作者Jonathan Zier
相关产品推荐
相关产品推荐

