繁体   English   中英

是否可以从执行多个get请求的async / await函数返回值(数组)?

[英]Is it possible to return a value(an array) from a async/await function which is doing multiple get requests?

我是Javascript的新手,并且正在解决程序的最后一部分。 但是,我在尝试从多个请求中获取和存储数据并将其推入要在函数外部使用的数组时遇到了异步等待功能的问题。 稍后,我想呈现此数组的内容(引号)并将其呈现给浏览器。 在内部循环的内部,我可以控制台记录我的数组,但是当我尝试返回它或使用函数本身时,我遇到了问题。 有任何想法吗?

我有一个URL数组,我可以用它来进行多次调用,因为我的数组中需要一定数量的项目,并且提供的API每次响应所得到的引号不会超过25个。



const getQuotes = () => {
  let completeQuotesArray = [];
  const quotesPromises = urls.map(async url => {
    const response = await axios.get(url);
    console.log(response);
    return response.data.quotes;
  });
  for (const quotesPromise of quotesPromises) {
    let quotesArray = await quotesPromise;
    for (let i = 0; i < quotesArray.length; i++) {
      let quote = quotesArray[i].body;

      if (quote.length < 150) {
        completeQuotesArray.push(quote);
      }
    } 
  }
  return completeQuotesArray;
}

这是一个使用Promise.all的示例,它并行请求您的网址: https : Promise.all

const quotesPromises = await Promise.all(urls.map(url => axios.get(url)))

代码中还有一些其他注释,用于解释并注销响应,因此您可以查看Promise.all工作:)响应数据与您的略有不同,但是我敢肯定您可以根据自己的需要进行调整。 我还建议您尝试使用try ... catch来确保已处理了承诺拒绝。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM