在表读取函数中,我调用另一个表来获取用户的电子邮件。看来,read调用是异步的,因此下面的变量没有必要的数据。
如何使嵌套读取中的代码等待完成?我觉得这段代码有点臭,有问题是从用户表中获取电子邮件并将其放入userDetail表的读取响应中的更好方法。
function read(query, user, request) {
var userId = user.userId.split(':')[1];
var email = null;
// we only want the user to get their row
console.log('Starting userdetail read ' + new Date().getTime());
query.where({userid : userId}).take(1);
request.execute({
success: function(results){
// This code is called but async
tables.getTable('user').where({id:userId}).read({
success: function(results){
console.log('email in read: ' + results[0].email +' '+ new Date().getTime());
email = results[0].email;
}
});
// This code runs before the above code
results[0].email = email;
console.log('email outside of read: ' + email +' '+ new Date().getTime());
console.log(results[0]);
request.respond();
}
});
}