【发布时间】:2020-09-15 17:11:08
【问题描述】:
我在 NodeJS 上运行一个服务器端脚本来更新数据库。我首先收集和汇总现有字段,然后更新新字段。
const User = require('./models/user');
// Summarize
User.summarizeAllUsers();
// Update
User.updateAllUsers();
函数是异步的,因为我要等待获取所有用户的返回:
UserSchema.statics.summarize = async function() {
let users = await this.getAllUsers();
// ...
}
很明显,summarize() 可能在update() 之后运行,我在日志中用console.log() 确认确实如此。我的解决方案是将函数拆分为两个不同的脚本,但有时我会忘记同时运行这两个脚本。
如何将它们保存在一个脚本中并确保一个在另一个之前完成?
【问题讨论】:
标签: node.js asynchronous async-await