如果有多个带有承诺的请求,我如何匹配对请求的响应?

How do I match a response to a request if there are multiple requests made with promises?

我正在发出多个承诺的请求,获取一组股票的历史定价数据。

因为响应可能不会以相同的顺序返回,我需要一种方法来知道哪个响应对应于哪个请求。返回的回复没有任何识别信息。

这是一个回复的样子:

{
    history: {
        day: {
            date: '1996-01-02', 
            open: 61.4063,
            close: 63.6719,
            high: 63.6875,
            low: 59.6406,
            volume: 10507600
        },
        ...
    }
}

这是我的要求:

var promises = [];
var symbols = ['MSFT', 'AAPL', 'GOOGL', 'FB', 'NVDA'];

symbols.forEach(function(symbol) {
  promises.push(axios.get('https://sandbox.tradier.com/v1/markets/history', {
    headers: {
      Accept: 'application/json',
      Authorization: 'Bearer ' + tradierACCESSTOKEN
    },
    params: {
      symbol: symbol,
      interval: 'daily',
      start: '2012-01-01'
    }
  }));
});

axios.all(promises)
  .then(function(responses) { 
    responses.forEach(function(response) {
      var data = response.data;
      // how do i know which response corresponds with the requested stock?
    });
  })
  .catch(error => console.log(error));

axios depends on a native ES6 Promise implementation

(source)

在 fulfillment 的情况下,response 包含一组单独的响应,其顺序与您将它们添加到 Promise.all 的顺序相同。这意味着 response[0] 将始终是对 'MSFT'.

请求的响应

If all of the passed-in promises fulfill, Promise.all is fulfilled with an array of the values from the passed-in promises, in the same order as defined in the iterable.

(MDN: Promise.all)

我会用一种不承诺的方法来做到这一点。 http.get 只是一个伪实现:

var request = function(symbol, cb){
    http.get('https://sandbox.tradier.com/v1/markets/history', {
        headers: { Accept: 'application/json', Authorization: 'Bearer ' + tradierACCESSTOKEN },
        params: { symbol: symbol, interval: 'daily', start: '2012-01-01' }
    }, cb);
};

var done = function(err, results){
   console.log(JSON.stringify(results));  // results => array same order as input
}

async.map(['MSFT', 'AAPL', 'GOOGL', 'FB', 'NVDA'], request, done);

不确定回调地狱在哪里。