异步/等待递归API调用 [英] Async/Await for recursive API Calls

查看:61
本文介绍了异步/等待递归API调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从分页的端点收集所有ID.我想等待所有呼叫结束,但似乎只能完成第一个呼叫并返回数据和对下一个呼叫的承诺.

I am trying to collect all the ids from a paginated endpoint. I want to wait for all the calls to finish but it seems to only finish the first call and return the data and a promise to the next call.

我如何等待所有呼叫返回.

How can I wait for all the calls to return.

const getSelectAllIds = async (url) => {
  let response = await axios.post(url);
  if (response.status === 200 && response.data.next != null) {
    console.log(`calling: ${response.config.url}`);
    return [
      ...response.data.results,
      await getSelectAllIds(response.data.next)
    ];
  }
};

const someFunction = async (url, data) => {
  const selectedIds = await getSelectAllIds(url);
  return selectedIds;
};

推荐答案

所有 async 函数始终会返回一个promise.因此, getSelectAllIds() someFunction()都将始终返回promise.该调用方将必须使用 .then() await 从诺言中获取价值.您不能使它们同步返回异步检索的值.Javascript不能那样工作.

All async functions return a promise, always. So both getSelectAllIds() and someFunction() will always return a promise. That caller will have to use .then() or await to get the value from the promise. You can't make them synchronously return the asynchronously retrieved value. Javascript does not work that way.

这就是nodejs中异步编码的工作方式.您永远无法将异步值转换为同步值.您必须使用异步机制来使用异步值.为了保证,这意味着调用方必须使用 .then()中的 await 来获取值.

That's how asynchronous coding works in nodejs. You can't ever turn an asynchronous value into a synchronous value. You have to use the asynchronous value using asynchronous mechanisms. For promises, that means the caller has to use await of .then() to get the value.

getSelectAllIds(someUrl).then(allIDs => {
     console.log(allIDs);
}).catch(err => {
     console.log(err);
});

请注意,如果 response.status 不是200,则不清楚代码应如何处理.而且,您似乎并没有从最后一页收集数据,因为您没有如果没有 data.next ,则不要将数据添加到数组中.

Note, it's not clear what you expect your code to do if response.status is not 200. And, it also looks like you're not collecting the data from the last page because you don't add the data into the array if there's no data.next.

这篇关于异步/等待递归API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆