2016-10-03 3 views
0

나는 nodejs 및 redis API 서비스를 만들고 있는데, 아래 코드를 작성하여 날짜 범위의 개별 날짜를 찾은 다음 각 날짜의 타임 슬롯을 가져 와서 redis로 저장하십시오.이상한 forjach nodejs의 각 동작

문제는 forEach 내부에서 console.log("Keys :"+key)을 수행하고 같은 forEach 내부의 키를 확인하지만 루프가 개별 기능을 개별적으로 실행하고 있습니다.

내가 여기에 더 문제를

//API to get slot for a particular date range 
app.get('/listcapacity/:ticketid/:fromdate/:todate', function(req, res) { 
    var id = req.params.ticketid; 
    var fromdate = req.params.fromdate; 
    var todate = req.params.todate; 
    var key = null; 
    var username = 'foo'; 
    var password = 'foobar'; 
    var result = {}; 
    var data_output = []; 
    var currentDate = new Date(fromdate); 
    var between = []; 
    var end = new Date(todate); 

    while (currentDate <= end) { 
     var tempdate = new Date(currentDate).toISOString(); 
     var dump = tempdate.toString().split("T"); 
     between.push(dump[0]); 
     currentDate.setDate(currentDate.getDate() + 1); 
    } 

    between.forEach(function(entry) { 
     key = id+entry+"list"; 
     console.log("Keys: " + key); 
     client.exists(key, function(err, reply) { 
      if (reply === 1) { 
       console.log("Key : " + key + " Found"); 
       client.get(key, function(err, reply) { 
        var output = JSON.parse(reply); 
        data_output = data_output.concat(output); 
       }); 
      } else { 
       console.log("Key : " + key + " Not Found"); 

       process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; 
       var slot_url = "https://" + username + ":" + password + "@testapi.foobar.com/1/timeslots?productId=" + id + "&fromDate=" + entry + "&toDate=" + entry; 
       request({ 

        url: slot_url, 
        json: true, 
        headers: headers 
       }, function(error, response, body) { 
        if (!error && response.statusCode === 200) { 
         var data = []; 
         try { 
          var temp = {}; 
          body.data.forEach(function(tempslots) { 
           temp['date'] = tempslots['date']; 
           temp['timeslots'] = tempslots['timeslots']; 
           data = data.concat(temp); 
          }); 
          client.set(key, JSON.stringify(data)); 
          data_output = data_output.concat(data); 
         } catch (err) { 

          console.log(err.message); 

         } 
        } else { 
         console.log("Something went wrong!! " + error.message); 
        } 
       }) 
      } 
     }); 
    }); 
    result['data'] = data_output; 
    result['response'] = 1; 
    result['message'] = 'Capacity list fetched successfully!'; 
    res.json(result); 

}); 

을 설명하는 코드와 콘솔 출력을 부착 및 AM 콘솔 출력

Keys: 5212016-10-01list 
Keys: 5212016-10-02list 
Keys: 5212016-10-03list 
Keys: 5212016-10-04list 
Keys: 5212016-10-05list 
Key : 5212016-10-05list Not Found 
Key : 5212016-10-05list Not Found 
Key : 5212016-10-05list Not Found 
Key : 5212016-10-05list Not Found 
Key : 5212016-10-05list Found 

레디 스에 확인하는 것이 아니라 때 키 값을 볼 수 있듯이 마지막 값을 얻는 곳 내에서 매우 동일한 루프로 키를 정의 할 때 올바른 값을 콘솔에 인쇄하고있는 것과 같습니다.

답변

1

문제는 redis 작업은 비동기입니다. 콜백은 다음 틱에서 실행됩니다. 그래서 그 시간에 열쇠 변수는 마지막 변수입니다.

로컬 변수를 사용해야합니다.