2016-11-16 32 views
0

如果我對async.map進行了一系列調用,結果是否保證了順序?或者結果只是請求完成的順序?例如async.map保證結果是按順序傳遞的嗎?

var requestList = [ 
    { method: 'GET', url: '/something1' }, 
    { method: 'GET', url: '/something2' }, 
    { method: 'GET', url: '/something3' }]; 

// async map the requests together, and handle the result in 
// the callback. 
async.map(requestList, function(obj, callback) { 
    request(obj, function(error, response, body) { 
     if(!error && response.statusCode == 200) { 
      var body = JSON.parse(body); 
      callback(null, body); 
     } else { 
      callback(error || response.statusCode); 
     } 
    }); 
}, function(err, result) { 
    if(err) { 
     console.log('Error!'); 
    } else { 
     // is result guarenteed to be in the order: [/something1, /something2, /something3] ? 
    } 
}); 
+1

是的,順序是迭代器和數組的保證。嘗試保持對象鍵的順序 – megawac

回答

0

如果它傳遞了一個數組,我認爲它總是按順序排列的。 並根據官方文檔 '如果map傳遞一個Object,結果將是一個Array。結果大致將按照原始對象的按鍵順序排列(但這可能因JavaScript引擎而異)'。 該文檔沒有提及數組,因此可以安全地假定該訂單將被保留。

相關問題