CNode

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

Llsmsnail发布于13 年前最后回复13 年前5 回复4544 浏览0 收藏
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)

A
alaaf#1·13 年前

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

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

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

A
alaaf#4·13 年前
引用 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#5·13 年前
引用 alaaf这个是异步的,console.log 在 orderShopList 赋值前就被调用了。console.log值难道不应该是 "[]"么?

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

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