找回密码
 免费注册

[TypeScript] ES6 async 函数

[复制链接]
admin 发表于 2024-2-1 01:06:03 | 显示全部楼层 |阅读模式
async 是 ES7 才有的与异步操作有关的关键字,和 Promise , Generator 有很大关联的。async 函数返回一个 Promise 对象,可以使用 then 方法添加回调函数。async 函数中可能会有 await 表达式,async 函数执行时,如果遇到 await 就会先暂停执行 ,等到触发的异步操作完成后,恢复 async 函数的执行并返回解析值。
  1. async function helloAsync(){
  2.     return "helloAsync";
  3.   }
  4.   
  5. console.log(helloAsync())  // Promise {<resolved>: "helloAsync"}

  6. helloAsync().then(v=>{
  7.    console.log(v);         // helloAsync
  8. })
复制代码
await
await 操作符用于等待一个 Promise 对象, 它只能在异步函数 async function 内部使用。
  1. function testAwait(){
  2.    return new Promise((resolve) => {
  3.        setTimeout(function(){
  4.           console.log("testAwait");
  5.           resolve();
  6.        }, 1000);
  7.    });
  8. }

  9. async function helloAsync(){
  10.    await testAwait();
  11.    console.log("helloAsync");
  12. }
  13. helloAsync();
  14. // testAwait
  15. // helloAsync
复制代码


返回值
返回 Promise 对象的处理结果。如果等待的不是 Promise 对象,则返回该值本身。
如果一个 Promise 被传递给一个 await 操作符,await 将等待 Promise 正常处理完成并返回其处理结果。
  1. function testAwait (x) {
  2.   return new Promise(resolve => {
  3.     setTimeout(() => {
  4.       resolve(x);
  5.     }, 2000);
  6.   });
  7. }

  8. async function helloAsync() {
  9.   var x = await testAwait ("hello world");
  10.   console.log(x);
  11. }
  12. helloAsync ();
  13. // hello world
复制代码
正常情况下,await 命令后面是一个 Promise 对象,它也可以跟其他值,如字符串,布尔值,数值以及普通函数。
  1. function testAwait(){
  2.    console.log("testAwait");
  3. }
  4. async function helloAsync(){
  5.    await testAwait();
  6.    console.log("helloAsync");
  7. }
  8. helloAsync();
  9. // testAwait
  10. // helloAsync
复制代码

await针对所跟不同表达式的处理方式:
  • Promise 对象:await 会暂停执行,等待 Promise 对象 resolve,然后恢复 async 函数的执行并返回解析值。
  • 非 Promise 对象:直接返回对应的值。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 免费注册

本版积分规则

QQ|Archiver|手机版|小黑屋|信息共享网

GMT+8, 2024-5-15 01:38 , Processed in 0.073998 second(s), 18 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表