• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
向阳花7
博客园    首页    新随笔    联系   管理    订阅  订阅
前端异步编程——async/await

  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();

 

posted on 2023-10-28 17:07  向阳花7  阅读(171)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3