需求:要赋值的变量是 last_idfunction foo() { var last_id = 'AAAA' // mongodb Model ItemModel.find((err, items) => { last_id = 'BBBB' console.log(`LOG_1: ${last_id}`) // [结果正确]: BBB }) console.log(`LOG_2: ${last_id}`) // [结果不是想要的]: AAA}问题:如何解决?可参考文档?
1 回答
呼如林
TA贡献1798条经验 获得超3个赞
因为你的这段代码执行之前,
ItemModel.find((err, items) => {
last_id = 'BBBB'
console.log(`LOG_1: ${last_id}`) // [结果正确]: BBB
})
你的这段代码执行了
function foo() {
var last_id = 'AAAA'
console.log(`LOG_2: ${last_id}`) // [结果不是想要的]: AAA
}
所以呢,你需要等第一步的代码执行完之后再执行最后的console.log()
改成这样
function foo() {
var last_id = 'AAAA'
// mongodb Model
let data = new Promise((resolve,reject)=>{
ItemModel.find((err, items) => {
last_id = 'BBBB'
console.log(`LOG_1: ${last_id}`)
})
})
data.then(()=>{
console.log(`LOG_2: ${last_id}`)
})
}
添加回答
举报
0/150
提交
取消
