gpt4 book ai didi

javascript - 如果有多个带有 promise 的请求,我如何匹配对请求的响应?

转载 作者:行者123 更新时间:2023-11-30 11:37:25 26 4
gpt4 key购买 nike

我正在发出多个 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 )

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

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com