我有一个使用 Axios 调用的端点,响应如下所示(例如):
items: [
{
url: "https://api.example1...",
expirationDate: "2019-11-15T00:00:00+01:00"
},
{
url: "https://api.example2...",
expirationDate: "2019-12-20T00:00:00+01:00"
},
{
url: "https://api.example3...",
expirationDate: "2020-01-17T00:00:00+01:00"
},
...等等。
如果我在浏览器中访问其中一个 url:s,则 JSON 的结构为:
fooBar: {
url: "https://api.foo...",
id: "123",
type: "INDEX",
source: "Foobar",
quotes: {
url: "https://api.bar..."
}
},
我需要动态获取 items:[] 中前两个 url:s 的引号,因为当“expirationDate”早于今天的日期时它们会消失。 如何才能实现这一目标?提前致谢!
最佳答案
如果我正确理解了要求,您需要:
- 获取项目列表
- 获取前两项的项目详细信息(以提取报价链接)
- 获取前两项的报价
您可以使用 promise 链来执行这些维护顺序的操作:
const getQuotes = (item) => axios.get(item.url)
.then(resp => axios.get(resp.data.fooBar.quotes.url));
axios.get('/items') // here should be the url that you use to get items array
.then(resp => resp.data.slice(0, 2).map(getQuotes))
.then(quotes => Promise.all(quotes))
.then(quotes => {
console.log(quotes);
});
关于javascript - 如何构建 JSON 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58859093/