我正在发出多个带有 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/