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