为什么在闭包内设置的值在闭包外不能使用?
 发布于 12 年前  作者 lsmsnail  4399 次预览  最后一次回复是 12 年前  来自  
var orderList = doc.orderList;
        var orderShopList = new Array();
        orderList.forEach(function(oneOrder){
            Shop.findOne({'name': oneOrder.shopName},function(err,shop){
                orderShopList[orderShopList.length] = shop;
                console.log(orderShopList);//有数值
            })
        })
       console.log(orderShopList);//打印为null

求教这是为什么,orderList是一个对象数组,orderShopList最终不是应该有数值吗?

5 回复
alaaf

这个是异步的,console.log 在 orderShopList 赋值前就被调用了。console.log值难道不应该是 "[]"么?

lsmsnail

是哦,一时没想到,谢谢

lsmsnail

那如果我希望console.log 在 orderShopList 赋值之后被调用需要怎么写?

alaaf

@lsmsnail

var orderList = doc.orderList; var orderShopList = new Array(); var outputFunction= function(){ console.log(orderShopList); } orderList.forEach(function(oneOrder){ Shop.findOne({‘name’: oneOrder.shopName},function(err,shop){ orderShopList[orderShopList.length] = shop; outputFunction(); }) })

lsmsnail

@alaaf 我是希望在循环执行完后打印,而不是每次赋值的时候打印