回调中的NodeJS Local变量 [英] NodeJS Local variable in callback
问题描述
我,
我知道,关于SO的信息很多,但是我找不到适合我情况的正确答案。
I, I know, there is a lot information about this on SO, but I didn't find the right answer for my situation.
我有这段代码:
for(var i=0; i < shop.collections.length; i++){
if(!shop.collection[i].active){
var data = {
name: shop.collection[i].name,
visible: true
};
myOwnService.createCollection(data, accessToken, function(err, response, body){
shop.collections[i].serviceId = body.id;
})
}
我的问题是商店
在 myOwnService.createCollection()
服务中未定义。在回调中访问 shop
变量的正确方法是什么,那么如何更新对象以便保存结果?
My problem is that shop
is undefined in the myOwnService.createCollection()
service. What is the right way to access the shop
variable in the callback, so how I can update the object so I can save the result?
推荐答案
shop
在 myOwnService.createCollection $ c的父范围内
shop
is in the parent scope of the myOwnService.createCollection
function hence it is accessible inside it.
上面代码中唯一的问题是 i
c $ c> callback 始终是最后一个值,因为它将在事件循环后执行。
Only issue in above code is i
used in callback
which will always be the last value as it will be executed after event loop.
使用围绕
包装器,以便可以传递 myOwnService.createCollection
的IIFE i
的范围。
Use IIFE
wrapper around myOwnService.createCollection
so that scope of i
could be passed.
for (var i = 0; i < shop.collections.length; i++) {
if (!shop.collection[i].active) {
var data = {
name: shop.collection[i].name,
visible: true
};
(function(i) {
myOwnService.createCollection(data, accessToken, function(err, response, body) {
shop.collections[i].serviceId = body.id;
});
})(i);
}
}
这篇关于回调中的NodeJS Local变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!