NodeJS回调中shop变量未定义问题的解决方案咨询
Hey there, let's break down what's going wrong here and fix it step by step!
First, there are two key issues causing your problem:
- Typo: You're looping over
shop.collections(plural), but inside the loop you wroteshop.collection[i](singular). This will directly lead to a "property not found" error, which might make you mistakenly thinkshopis undefined. - Closure Trap: The
ideclared withvaris a function-scoped variable—all iterations of the loop share the samei. SincemyOwnService.createCollectionis asynchronous, by the time its callback runs, the loop has already finished, andiequalsshop.collections.length. At that point,shop.collections[i]becomesundefined, which also messes up your access toshop-related properties.
Here are two solid fixes to resolve this:
Solution 1: Replace var with let to use block scoping
let creates a separate scope for each loop iteration, so the callback will get the correct index value when it executes:
for(let i=0; i < shop.collections.length; i++){ if(!shop.collections[i].active){ const data = { "name": shop.collections[i].name, "visible": true }; myOwnService.createCollection(data, accessToken, function(err, response, body){ if (!err) { // Don't forget error handling to avoid new bugs shop.collections[i].serviceId = body.id; } }) } }
Solution 2: Use forEach to avoid closure issues entirely
The forEach callback creates an independent scope for each element. You can directly use the current collection object, no need to worry about index problems at all:
shop.collections.forEach(function(collection) { if(!collection.active){ const data = { "name": collection.name, "visible": true }; myOwnService.createCollection(data, accessToken, function(err, response, body){ if (!err) { collection.serviceId = body.id; } }) } });
A quick extra tip: Always add error handling (like the if (!err) checks above). If the createCollection request fails, body might be undefined, which would cause another set of errors.
内容的提问来源于stack exchange,提问作者NVO
相关产品推荐
相关产品推荐

