javascript重试异步等待



我有多个异步函数,它们都会向服务器发送请求,如果出现错误,他们会抓住它,然后重试该函数,这些函数依赖于前一个函数的数据,所以它们必须一个接一个地发送,问题是每当我调用这些函数时出现错误,它会按照我的意愿不断重试,但它会继续执行下一个函数,而不是等待上一个函数返回解析的响应。

const request1 = async () => {
try {
const data = await rp.get(link, options)
return data
} catch (err) {
request1()
}
}
const request2 = async (data) => {
try {
const data = await rp.get(link, options)
return data
} catch (err) {
request2()
}
}
const getData = async() => {
await request1()
await request2()
})
getData()

每当我调用getData((函数时,它都会等待第一个请求,但即使它有错误,它也会立即处理第二个请求,而不是等待第一个问题得到解决,我还需要对我发送的所有请求进行try-catch,而不是一个,因为如果有错误,我只想重试那一步,而不是完整的

您没有返回重新调用

const request1 = async () => {
try {
const data = await rp.get(link, options)
return data
} catch (err) {
return await request1(); // i'm not sure if you need await here or not, worth testing
}
}

如果你没有从重新呼叫中返回,那么你所做的基本上与这个相同

const request1 = async () => {
try {
const data = await rp.get(link, options)
return data
} catch (err) {
request1(); // this does request 1 WITHOUT waiting for a result
}
return undefined;    
}

编辑:第一个是一个玩具示例,说明如果你不返回任何会发生什么

const rp = {
get: async function() {
await new Promise(r => setTimeout(r, 250));
this.count++;
if (this.count % 2 === 0) {
return this.count;
} else {
throw new Error('error: even')
}
},
count: 0
};
const request1 = async () => {
try {
const data = await rp.get();
console.log('data in request1', data);
return data
} catch (err) {
request1();
}
};
const request2 = async (data) => {
try {
const data = await rp.get();
console.log('data in request2', data);
return data
} catch (err) {
request2();
}
};
const getData = async() => {
console.log('starting request 1');
await request1();
console.log('starting request 2');
await request2()
};
getData();

这就是当你回来时会发生的事情:

const rp = {
get: async function() {
await new Promise(r => setTimeout(r, 250));
this.count++;
if (this.count % 2 === 0) {
return this.count;
} else {
throw new Error('error: even')
}
},
count: 0
};
const request1 = async () => {
try {
const data = await rp.get();
console.log('data in request1', data);
return data
} catch (err) {
return request1();
}
};
const request2 = async (data) => {
try {
const data = await rp.get();
console.log('data in request2', data);
return data
} catch (err) {
return request2();
}
};
const getData = async() => {
console.log('starting request 1');
await request1();
console.log('starting request 2');
await request2()
};
getData();

您将在第一个示例中注意到,request2在request1记录其数据之前启动,但在第二个示例中,对于return语句,request2直到request1获得数据之后才启动。

您可以创建一个全局请求函数,类似这样。

const globalRequest = async (link, options, retryCount=0) => {
try {
if(retryCount > 3) return "Some issue with the url";
const data = await rp.get(link, options)
return data;
} catch (err) {
logger.error(err)
await globalRequest(link, options, retryCount+1);
}
}

const getData = async() => {
for(let req of requests){
await globalRequest(req.link, req.options);
}
})
getData()

最新更新