Javascript变量作用域

需求:

要赋值的变量是 last_id


function 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

}

问题:


如何解决?

可参考文档?


慕婉清6462132
浏览 409回答 1
1回答

呼如林

因为你的这段代码执行之前,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}`)    }) }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript