2017-08-29 104 views
0

我對nodejs相當陌生,我有一個場景,當用戶點擊一個端點時,我需要進行兩個post調用。第一個API調用返回給我一個我應該在第二次調用中使用的URL。這是我寫過的用於完成這些後期調用的通用模塊。多個請求覆蓋變量值

// First call 
requester.post(options1).then(function(result1){ 
    var options2 = { 
     url: result1.url, 
     req: req, 
     res: res 
    } 
    ... 
    // Second Call 
    requestor.post(options2).then(function(result2) { 
    }) 
}) 

var requestor = { 
    post: function(options) { 
    url = options.url; 
    ... 

    var deferred = q.defer(); 

    ... 
    var post = request.post(url, data, function (error, response, body) { 
     if (!error && response.statusCode == 200) { 
     try { 
      deferred.resolve(body); 
     } 
     catch(e) { 
      deferred.reject(new Error('Request failed while processing request')); 
     } 
     } else { 
     deferred.reject({code: code}); 
     } 
    }) 
    ... 
    return deferred.promise; 
    } 
} 

我的問題是,當我有兩個請求在確切的微秒進來時,url變量被覆蓋。雖然第一個請求的「第二次調用」仍在進行中(並且在我的情況下最終會超時),但第二次請求的第二次調用將覆蓋url變量。請建議我應該修復/更改。

回答

1

它覆蓋url因爲url是一個全局變量

var requestor = { 
post: function(options) { 
    url = options.url; 

更改上面的代碼段將

var requestor = { 
post: function(options) { 
    var url = options.url;