【发布时间】:2020-08-03 11:49:16
【问题描述】:
我想让这段代码在收到错误 10 次之后继续尝试,在 10 次之后它应该停止尝试,而不是尝试它会显示一条消息,而不是出现错误, 所以我故意在那里抛出一个错误,让它给出错误和一个for循环,但它一直在尝试单独的错误消息,如下图所示,所以我怎样才能添加那个for循环以便它可以停止尝试运行函数和改为显示消息?
这是我的代码:
async function getQuote() {
loading();
const apiUrl = 'https://cors-anywhere.herokuapp.com/http://api.forismatic.com/api/1.0/?
method=getQuote&format=json&lang=en';
try {
const response = await fetch(apiUrl)
const data = await response.json();
// Changing the blank Author textfield to Unknown
if (data.quoteAuthor === ''){
authorText.innerText = 'Unknown';
} else {
authorText.innerText = data.quoteAuthor;
}
if (quoteText.innerText.length > 120){
quoteText.classList.add('long-quote');
} else {
quoteText.classList.remove('long-quote');
}
quoteText.innerText = data.quoteText
//Stop loader, Show Quote
complete();
throw new Error("Opss!")
} catch(error) {
for(let i=0; i < 10 ; i++){
getQuote();
// console.log('something went wrong!', error);
}
}
}
【问题讨论】:
-
这样做:npmjs.com/package/promise-retry 如果您无法捆绑它,您可以检查源代码并复制它。这是非常简单的机械。你需要让你的函数返回一个 Promise。
-
@Adamazad 谢谢你的建议,它真的很有帮助,但我想通过 JS 使用 for 循环了解传统
标签: javascript api for-loop infinite-loop