javascript - 如何构建 JSON 调用

标签 javascript node.js json

我有一个使用 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/

相关文章:

node.js - eslint 8 以表彰顶级等待

json - Node.js错误: (node:9748) UnhandledPromiseRejectionWarning: Unhandled promise rejection

javascript - jquery ajax 通过 mvc 操作方法的空响应

javascript - 如何将带有序数后缀的数字转换为javascript中的数字

JavaScript( Node )错误 : Unexpected token function

javascript - d3.json 无法从 json 文件读取多个对象

java - HttpRequestHandlingMessagingGateway JSON 数组有效负载

javascript - 无法访问对象文字中另一个函数中的变量

javascript - 在 window.getSelection() 之后获取下一个字符

javascript - 使用javascript提取和粘贴字符串的一部分