javascript - 如果有多个带有 Promise 的请求,如何将响应与请求匹配?

标签 javascript ajax promise axios

我正在发出多个带有 promise 的请求,获取一系列股票的历史定价数据。

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

以下是一个响应:

{
    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 )

在实现的情况下,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 )

关于javascript - 如果有多个带有 Promise 的请求,如何将响应与请求匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43866153/

相关文章:

javascript - 减少 Promise.all?

javascript - Directus API SDK : How to get items with M2M filter

javascript - AngularJs ng-href 动态链接的范围未更新/工作

javascript - 使用 angularjs 获取休息服务

java - 使用ajax推送通知

javascript - Promise.all 中获取失败,未捕获错误

javascript - 如何根据所选 ListView 项目使按钮表现不同?

javascript - jQuery 颜色框调整大小

jquery - 在ajax成功函数中使用$(this)

javascript - 如果使用 then ,是否需要在 Promise 中嵌套 catch?