javascript 重试异步等待

Ken*_*lly 1 javascript node.js async-await

我有多个异步函数,它们都向服务器发送请求,如果有错误,它们会捕获它然后重试该函数,这些函数依赖于前一个函数的数据,因此它们必须一个接一个地发送,问题是每当我调用这些函数并且出现错误时,它会像我想要的那样不断重试,但它会继续执行下一个函数,而不是等待前一个函数返回已解决的响应。

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()
Run Code Online (Sandbox Code Playgroud)

每当我调用 getData() 函数时,它都会等待第一个请求,但即使它有错误,它也会在第二个请求之后立即移动,而不是等待第一个请求解决,我也需要一个 try catch for all我发送的请求而不是一个,因为如果出现错误,我只想重试这一步,而不是完整的

TKo*_*KoL 5

你不回电

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
    }

}
Run Code Online (Sandbox Code Playgroud)

如果您不从重新调用中返回,那么您所做的与此基本相同

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;    
}
Run Code Online (Sandbox Code Playgroud)

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

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
    }

}
Run Code Online (Sandbox Code Playgroud)

这是当您返回时会发生的情况:

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;    
}
Run Code Online (Sandbox Code Playgroud)

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