首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >抛出错误后继续执行Promise.all吗?

抛出错误后继续执行Promise.all吗?
EN

Stack Overflow用户
提问于 2022-06-30 23:53:26
回答 3查看 133关注 0票数 1

我正在尝试从WordPress开发人员参考站点获取JSON数据。我需要搜索关键字,而不知道它是函数、类、钩子还是方法,这是我需要获取的url的一部分。所以我使用Promise.all循环所有可能的urls。如果response.status <= 299立即抛出错误,如果响应正常,则继续执行.then。很好,但有时如果存在JSON,它会返回ok状态,并且只返回一个空数组。因此,我需要检查JSON数据是否是一个空数组,在第一部分中我似乎不能这样做。据我所知,我只能在第二部分查询。如果它抛出错误,它就不会继续尝试其他urls。有什么建议吗?

代码语言:javascript
运行
复制
var keyword = 'AtomParser';
const refs = ['function', 'hook', 'class', 'method'];

// Store the promises
let promises = [];

// Cycle through each type until we find one we're looking for
for (let t = 0; t < refs.length; t++) {
  const url =
    'https://developer.wordpress.org/wp-json/wp/v2/wp-parser-' +
    refs[t] +
    '?search=' +
    keyword;
  // console.log(url);
  promises.push(fetch(url));
}
Promise.all(promises)
  .then(function(response) {
    console.log(response[0]);

    // Get the status
    console.log('Status code: ' + response[0].status);
    if (response[0].status <= 299) {
      // The API call was successful!
      return response[0].json();
    } else {
      throw new Error('Broken link status code: ' + response[0].status);
    }
  })
  .then(function(data) {
    // This is the HTML from our response as a text string
    console.log(data);

    // Make sure we have data
    if (data.length == 0) {
      throw new Error('Empty Array');
    }

    // ref
    const reference = data[0];

    // Only continue if not null or empty
    if (reference !== null && reference !== undefined && data.length > 0) {
      // Success
      // Return what I want from the reference
    }
  })
  .catch(function handleError(error) {
    console.log('Error' + error);
  });

是否有办法在第一部分中获取JSON数据,以便在检查响应状态时检查它是否在数组中?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72823125

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档