await
我的主要代码是:
app.post('/sms',async function(req,res){
try{
worker=await worker.updateWorker('+18005559999',process.env.TWILIO_OFFLINE_SID);
responseValue="/sms: worker "+worker.friendlyName+" updated to: "+worker.activityName;
console.log(responseValue);
res.status(200).send();
}
catch(err){
console.log("/sms error: "+err);
}
}
worker.updateWorker()
async updateWorker(contact_uri,activitySid){
console.log("updateWorker: getting workerSid from database");
workerSid=await database.getWorkerSid(contact_uri);
console.log("updateWorker: workerSid is "+workerSid);
worker=await this.updateWorkerFromSid(workerSid,activitySid);
console.log("updateWorker: worker's friendlyName is "+worker.friendlyName);
return worker;
}
database.getWorkerSid()
是:
getWorkerSid(contact_uri){
return new Promise(function(resolve,reject){
sequelize.query("select * from worker where contact_uri='"+contact_uri+"'",
{ type: sequelize.QueryTypes.SELECT})
.then(result=>{
if(result.length==0){
resolve(null);
}
else{
resolve(result[0].sid);
}
})
.catch(err=>reject(err));
});
}
this.updateWorkerFromSid()
async updateWorkerFromSid(workerSid,activitySid){
var worker;
try{
worker=await this.workspace.workers(workerSid)
.update({
activitySid:activitySid
});
console.log("updateWorkerFromSid: worker has been updated to activity: "+worker.activityName);
return worker;
}
catch(err){
console.log("updateWorkerFromSid error: "+err);
}
finally{
return worker;
}
}
updateWorker: getting workerSid from database
Executing (default): select * from worker where contact_uri='+18005559999'
/sms error: ReferenceError: workerSid is not defined
sequelize.query()
请来
database.getWorkerSid()
,但执行过程将继续进行,而无需等待查询承诺得到解决,并在线:
console.log("updateWorker: workerSid is "+workerSid);
这个
workerSid
未定义,因此会发生崩溃,错误会传播回主代码中的try/catch块。
基本上,我想做的是:
-
收到
工人阶级
contact_uri
-
使用
工人阶级
-
如何设置async/await以确保事件按此顺序发生?