在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/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
}

問(wèn)題:

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

因?yàn)槟愕倪@段代碼執(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
編輯回答
菊外人

這個(gè)其實(shí)和異步有關(guān):

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

可以使用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
編輯回答
別傷我

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

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

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

2018年4月1日 13:57