为了账号安全,请及时绑定邮箱和手机立即绑定

Javascript变量作用域

Javascript变量作用域

慕婉清6462132 2019-02-21 13:19:06
需求:要赋值的变量是 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}`) 

   }) 

}


查看完整回答
反对 回复 2019-02-26
  • 1 回答
  • 0 关注
  • 408 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号