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
}

问题:

  1. 如何解决?
  2. 可参考文档?
阅读 2.6k
4 个回答

因为你的这段代码执行之前,

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}`) 
   }) 
}

这是异步操作 你直接在回调里面操作不行吗?

这个其实和异步有关:

function foo() {
    var last_id = 'AAAA'
    // mongodb Model
    ItemModel.find((err, items) => {
        last_id = 'BBBB'
        console.log(`LOG_1: ${last_id}`) // 结果为 BBB,这个是在成功查找到数据后才会被执行,是异步操作,所以会在下面的console执行之后才会被执行
    })
    console.log(`LOG_2: ${last_id}`) // 结果 AAA 先执行这个
}

可以使用async函数

async function foo() {
    var last_id = 'AAAA'
    // mongodb Model
    await ItemModel.find((err, items) => {
        last_id = 'BBBB'
        console.log(`LOG_1: ${last_id}`)
    })
    console.log(`LOG_2: ${last_id}`)
}

这个真是好多方法,比如 promise 、 async await, generator, 回调,但是原理就一个 最后那句话最后执行

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题