You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Typo: You're looping over shop.collections (plural), but inside the loop you wrote shop.collection[i] (singular). This will directly lead to a "property not found" error, which might make you mistakenly think shop is undefined.
  2. Closure Trap: The i declared with var is a function-scoped variable—all iterations of the loop share the same i. Since myOwnService.createCollection is asynchronous, by the time its callback runs, the loop has already finished, and i equals shop.collections.length. At that point, shop.collections[i] becomes undefined, which also messes up your access to shop-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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:58:29