async await一些小结

// MDN: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function
  // async await 是基于promises的语法糖,使异步代码更易于编写和阅读。
  // 通过使用它们,异步代码看起来更像是老式同步代码

  /***
   * async 关键字,放在函数声明之前,使其成为 async function
   * 调用该函数会返回一个 promise
   * ***/
  async function hello() {
    return 'Hello'
  }

  hello().then(s => {
    console.log(s)
  })

  hello().then(console.log)

  /*****
   * await 关键字 只在async function里面才起作用。
   * 它可以放在任何异步的,基于 promise 的函数之前。
   * await 关键字使JavaScript运行时暂停于此行,允许其他代码在此期间执行,直到异步函数调用返回其结果。一旦完成,您的代码将继续从下一行开始执行。
   * ****/ 
  async function hello2() {
    return await Promise.resolve("Hello2");
  };

  hello2().then(console.log);

  /****
   * await 普通值
   * ***/ 
  async function hello3() {
    return await 'Hello3'
  };

  hello3().then(console.log)

  /***
   * 添加错误处理 可添加try...catch 或者 在hello4().catch中处理 
   * ***/ 
  async function hello4(a) {
    a / b

    return await 'Hello4'
  }

  hello4().then(console.log).catch(e => {
    console.log('出错了...', e)
  })

  // 没有使用async的普通函数,使用await会报错
  // function testAwait() {
  //   // 报错1
  //   await Promise.resolve(2)

  //   return new Promise((resolve, reject) => { 
  //     // 报错2
  //     await Promise.resolve(2)
  //     resolve(4)
  //   })
  // }
原文地址:https://www.cnblogs.com/zkpThink/p/14479062.html