Node.js 同时使用Promise和async
我对Node.js有点陌生,我试图理解使用错误处理和等待正确响应的想法 所以我从一个网页请求一些数据,然后如果我得到了数据,它就完成了,但如果没有,它应该去重试,并再次获得,直到达到最大数量 这是我的密码:Node.js 同时使用Promise和async,node.js,asynchronous,promise,async-await,Node.js,Asynchronous,Promise,Async Await,我对Node.js有点陌生,我试图理解使用错误处理和等待正确响应的想法 所以我从一个网页请求一些数据,然后如果我得到了数据,它就完成了,但如果没有,它应该去重试,并再次获得,直到达到最大数量 这是我的密码: const getData=(url)=>{ 返回新承诺((解决、拒绝)=>{ 常量选项={ 方法:“GET”, url:“我的url”, 标题:{ 接受:'application/json' } } 函数回调(错误、响应){ 如果(!错误){ 让data=response.data; 返
const getData=(url)=>{
返回新承诺((解决、拒绝)=>{
常量选项={
方法:“GET”,
url:“我的url”,
标题:{
接受:'application/json'
}
}
函数回调(错误、响应){
如果(!错误){
让data=response.data;
返回解析({success:true,data:data,statusCode:response.statusCode})
}否则{
返回拒绝({success:false,error:error})
}
}
请求(选项、回调)
})
}
在retry()
中,您需要迭代(使用while循环)或递归(使用retry()调用自身),但不能同时进行迭代和递归
如果选择递归,请确保返回retry()
无需传递next
函数,因为retry()
将返回承诺。因此,在retry的调用者中,您可以链接retry()。然后(…)
或异步/等待等效项
应该采取以下措施:
const retry = async(max, count) => {
count = count || 0;
let result;
if(count >= max) { // top test; ensures that getData() isn't run even if say `retry(5, 10)` was accidentally (or deliberately) called.
throw new Error('max reached'); // will not be caught below and will terminate the trying.
}
try {
result = await getData(url);
if(result.code !== 200) {
throw new Error(`getData() was unsuccessful (${result.code})`); // will be caught and acted on below
}
return result.data; // will bubble upwards through the call stack to retry's original caller
}
catch(error) {
// all errors ending up here qualify for a retry
console.log(error.message, `retrying... (${count})`);
return retry(max, count + 1); // recurse
}
}
// call as follows
retry(5).then(function(data) {
// work with `data`
}).catch(function(error) {
console.log(error);
// take remedial action, rethrow `error`, or do nothing
});
实际上,您可能会选择在重试之间引入延迟,以便给数据源更多的时间来更改状态。在retry()
中,您既有迭代(while循环)也有递归(重试调用本身)。其中一个(书写正确)可以完成这项工作,但不是两个都可以。