【问题标题】:How to chain API requests that return Promise which has a field in array?如何链接返回 Promise 的 API 请求,该请求在数组中有一个字段?
【发布时间】:2021-04-18 03:10:26
【问题描述】:

需要链接 API 调用,以便在第一个 API 调用 Promise 中返回的数据随后用于调用另一个 API 调用。 Api 调用返回 Json 数据,然后使用数组格式的字段,其中每个数组调用另一个 API 调用,这会继续到多个级别和几个 API 调用。 我知道嵌套 API 调用是一种不好的做法,最好使用 async 和 await 或链接承诺?但是在返回的数据有一个数组的情况下,我想继续为该数组中的每个元素进行另一个 API 调用,每个元素都会导致多个带有数组数据的承诺,这再次需要对每个元素进行 API 调用,并且以此类推。

【问题讨论】:

  • 分享你的代码你到目前为止所尝试的,...
  • 这听起来像是 Promise.all() 的工作。你调查过吗? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 请让您的问题更清楚,并分享您到目前为止所尝试的内容
  • @TaylorRahul 在下面我嵌套的地方添加代码,但我想有效地重写它。 client.workspaces.getWorkspaces({ opt_pretty: true }).then((wrkspaces) => {wrkspaces.data.map((wrkspace) =>client.projects.getProjects({ workspace: rkspace.gid, opt_pretty: true }) .then((Projects) => {console.log(Projects); Projects.data.map((Project) =>client.tasks .getTasksForProject(Project.gid, { opt_pretty: true }).then((tasks) = > { tasks.data.map((task) => {client.tasks.getTask(task.gid, { opt_pretty: true }).then((taskdetails) => { ....

标签: javascript node.js api promise async-await


【解决方案1】:

为每个 API 调用创建一个 Promise 并使用 Promise.all 之类的东西

let urls = [
  'https://api.com/product/1',
  'https://api.com/product/2',
  'https://api.com/product/3',
];

// map every url to the promise of the fetch
let requests = urls.map(url => fetch(url));

// Promise.all waits until all jobs are resolved
Promise.all(requests)
  .then(responses => responses.forEach(
    response => alert(`${response.url}: ${response.status}`)
  ));

【讨论】:

    猜你喜欢
    • 2019-01-02
    • 1970-01-01
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 2016-01-30
    相关资源
    最近更新 更多