简体   繁体   English

async/await 在 JS 中执行下一行之前不等待

[英]async/await doesn't wait before executing next line in JS

I found an exponential backoff function which is supossed to retry an API fetch in case of an error in exponential delays:我发现了一个指数退避 function 在指数延迟出错的情况下重试 API 提取:

async function exponentialBackoff(toTry, max, delay) {
    console.log('max', max, 'next delay', delay);
    try {
        let response = await toTry()
        return response;
    } catch (e) {
        if (max > 0) {
            setTimeout(function () {
                exponentialBackoff(toTry, --max, delay * 2);
            }, delay);

        } else {
            console.log('maximum amount of tries exceeded', e);
            return e;
        }
    }
}

I then use the function with the help of GA API library to make a request.然后我在 GA API 库的帮助下使用 function 发出请求。 On purpose I am sending an invalid body to make the request fail:我故意发送无效正文以使请求失败:

response = await exponentialBackoff(async function () {
                    return await gapi.client.request({
                        path: 'https://analyticsadmin.googleapis.com/v1beta/properties',
                        method: 'POST',
                        body: property
                    })
                }, 10, 30)

console.log("NEXT LINE"); 

What I would expect is that the exponential backoff will run out of all attempts (10) and only after that it would execute the console log.我期望的是指数退避将用完所有尝试(10),并且只有在此之后它才会执行控制台日志。

What actually happens is that the console log gets executed right after first try.实际发生的是控制台日志在第一次尝试后立即执行。 What am I doing wrong there?我在那里做错了什么?

Thank you谢谢

  1. Promisify setTimeout and await it.承诺setTimeoutawait它。 A promisified variant is一个承诺的变体是

    function sleep(ms) { return new Promise(res => { setTimeout(res, ms); }); }
  2. await exponentialBackoff in the catch block.catch块中await exponentialBackoff退避。

The fixed code is:固定代码是:

function sleep(ms) { return new Promise(res => { setTimeout(res, ms); }); }

async function exponentialBackoff(toTry, max, delay) {
    console.log('max', max, 'next delay', delay);
    try {
        let response = await toTry()
        return response;
    } catch (e) {
        if (max > 0) {
            await sleep(delay);
            return await exponentialBackoff(toTry, --max, delay * 2);    
        } else {
            console.log('maximum amount of tries exceeded', e);
            return e;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM