跳到主要内容
CNode

为什么在闭包内设置的值在闭包外不能使用?

社区
Llsmsnail发布于 13 年前最后回复 13 年前
545610
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)

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

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

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

@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(); }) })

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

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

A
alaaf#113 年前

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

参与回复

登录后即可参与回复。登录