鍍金池/ 問答/HTML/ Javascript變量作用域

Javascript變量作用域

需求:
要賦值的變量是 last_id

function foo() {
    var last_id = 'AAAA'
    // mongodb Model
    ItemModel.find((err, items) => {
        last_id = 'BBBB'
        console.log(`LOG_1: ${last_id}`) // [結(jié)果正確]: BBB
    })
    console.log(`LOG_2: ${last_id}`) // [結(jié)果不是想要的]: AAA
}

問題:

  1. 如何解決?
  2. 可參考文檔?
回答
編輯回答
維他命

因為你的這段代碼執(zhí)行之前,

ItemModel.find((err, items) => {
    last_id = 'BBBB'
    console.log(`LOG_1: ${last_id}`) // [結(jié)果正確]: BBB
})

你的這段代碼執(zhí)行了

function foo() {
    var last_id = 'AAAA'

    console.log(`LOG_2: ${last_id}`) // [結(jié)果不是想要的]: AAA
}

所以呢,你需要等第一步的代碼執(zhí)行完之后再執(zhí)行最后的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}`) 
   }) 
}
2017年7月16日 16:02
編輯回答
菊外人

這個其實和異步有關:

function foo() {
    var last_id = 'AAAA'
    // mongodb Model
    ItemModel.find((err, items) => {
        last_id = 'BBBB'
        console.log(`LOG_1: ${last_id}`) // 結(jié)果為 BBB,這個是在成功查找到數(shù)據(jù)后才會被執(zhí)行,是異步操作,所以會在下面的console執(zhí)行之后才會被執(zhí)行
    })
    console.log(`LOG_2: ${last_id}`) // 結(jié)果 AAA 先執(zhí)行這個
}

可以使用async函數(shù)

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}`)
}
2017年10月13日 08:55
編輯回答
別傷我

這個真是好多方法,比如 promise 、 async await, generator, 回調(diào),但是原理就一個 最后那句話最后執(zhí)行

2018年3月6日 08:22
編輯回答
野橘

這是異步操作 你直接在回調(diào)里面操作不行嗎?

2018年4月1日 13:57