且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

异步/等待函数中的 JavaScript Promise 解析最终的响应数组

更新时间:2022-05-19 08:44:06

有几个问题.一个是你永远不会resolve初始的Promise,除非进入else块.另一个是你应该每次返回递归的get_data调用,这样它就可以与初始的Promise正确链接.您也可以考虑避免 显式承诺构***模式 - get_items 已经返回了一个 Promise,所以没有必要再构造一个(get_items 内部也一样>、axios 调用也返回 Promises).

There are a few problems. One is that you never resolve the initial Promise unless the else block is entered. Another is that you should return the recursive get_data call every time, so that it can be properly chained with the initial Promise. You may also consider avoiding the explicit promise construction antipattern - get_items already returns a Promise, so there's no need to construct another one (same for the inside of get_items, axios calls return Promises too).

你可能会考虑一个普通的 while 循环,重新分配 next_url 字符串直到它是假的:

You might consider a plain while loop, reassigning the next_url string until it's falsey:

function get_items (baseURL) {
  const options = {
    baseURL: url,
    method: 'get'
  }
  // return the axios call, handle errors in the consumer instead:
  return axios(options)
    .then(res => res.data)
}

async function get_data() {
  const output = []
  let next_url = 'https://some_url.com/api/data'
  try {
    while (next_url) {
      const response = await get_items(next_url);
      output.push(...response.results)
      next_url = response.next;
    }
  } catch (e) {
    // handle errors *here*, perhaps
    console.log(e)
  }
  return output;
}

请注意,.catch 将导致 Promiserejected Promise 转换为 resolved 一个 - 你不想 .catch 到处都是,因为这会让调用者很难检测到错误.

Note that .catch will result in a Promise being converted from a rejected Promise to a resolved one - you don't want to .catch everywhere, because that will make it difficult for the caller to detect errors.