前端多线程处理——async/await

发布时间 2023-10-28 17:12:02作者: 向阳花7

  async 从字面上看就是“异步”,它放在函数定义之前,是使该函数在调用时开一个子线程,以不影响主线程的运行。

  而 await 经常和 async 组合使用,在 async 定义的函数中来等待需要时间运行的代码(如ajax请求、Promise对象)的运行结果,以做后续的处理。

  如下面的返回Promise对象的函数:

function print(delay, message) {
    return new Promise(function (resolve, reject) {            // 返回Promise对象
        setTimeout(function () {                               // 延迟执行函数
            console.log(message);
            resolve();
        }, delay);
    });
}

  如果需要运行通过,就需要经过then、catch、finally函数来执行响应的代码:

print(1000, "First").then(function () {            // 1秒之后输出“First”
    return print(2000, "Second");                  // 2秒之后输出“Second”
}).then(function () {
    return print(1000, "Third");                   // 1秒之后输出“Third”
}).then(function (){
    print(2000, "Fourth");                         // 2秒之后输出“Fourth”
});

   而使用 async/await 可以实现同样的效果,使用异步操作就像同步操作一样简单:

async function asyncFunc() {
    await print(1000, "First");
    await print(2000, "Second");
    await print(1000, "Third");
    await print(2000, "Fourth");
}
asyncFunc();

  而对于 Promise 中的异常处理,使用 try-catch 来实现:

async function asyncFunc() {
    try {
        await print(1000, "First");          //1秒后输出"First"
        });
    } catch (err) {
        console.log(err);                    //输出异常错误
    }
    try {
        await print(2000, "Second");         //2秒后输出"Second"
        });
    } catch (err) {
        console.log(err);                    //输出异常错误
    }
    try {
        await print(1000, "Third");          //1秒后输出"Third"
        });
    } catch (err) {
        console.log(err);                    //输出异常错误
    }
    try {
        await print(2000, "Fourth");         //2秒后输出"Fourd"
        });
    } catch (err) {
        console.log(err);                    //输出异常错误
    }
}
asyncFunc();