关于javascript:asyncawait笔记

37次阅读

共计 1461 个字符,预计需要花费 4 分钟才能阅读完成。

async/await

1.async 关键字只能放在函数前, 被 async 润饰的函数返回的是一个 promise,其值主动被包装在 promise 的 resolve 中

async function func() {return 1}

2.await 只能在 async 包裹的函数能应用,await 会让 JavaScript 引擎期待直到 promise 实现并返回后果

async function f() {let promise = new Promise((resolve, reject) => {setTimeout(() => resolve("done!"), 1000)
  });

  let result = await promise; // 期待,直到 promise resolve (*)

  alert(result); // "done!"
}

f();

async+await 相当于 promise.then,然而只会承受 resolve、不会解决 reject

3.try…catch 应用 try…catch 在包裹 await 来解决 promise 返回的 reject, 当遇到 reject 会间接跳到 catch 中

    async function fucntionTry() {
      try {let promiseResolve =await  new Promise((resolve,reject) => {setTimeout(()=>resolve('5 秒'),5000)
        })
        console.log(promiseResolve)
        let promiseReject = await  new Promise((resolve,reject) => {reject('I am Reject')
        })
        let promiseEnd = await new Promise((resolve,reject) => {resolve('Process End')
        })
        console.log(promiseEnd)
      } catch(err) {console.log('try catch', err)
      }
    }

    fucntionTry()

4.prmoise.all([]) 用于同时执行多个 promise,留神 promise.all 中的 promise 是异步执行的

async function PromiseAll() {
      try {
        let promiseArray = await Promise.all([new Promise((resolve,reject) => {resolve(1)}),
        new Promise((resolve,reject) => {resolve(2)}),
        new Promise((resolve,reject) => {resolve(3)}),
        new Promise((resolve,reject) => {resolve(4)}),
      ])
      console.log('promiseArray', promiseArray)
        let promiseErrArray = await Promise.all([new Promise((resolve,reject) => {resolve(5)}),
          new Promise((resolve,reject) => {reject(6)}),
          new Promise((resolve,reject) => {resolve(7)}),
          new Promise((resolve,reject) => {resolve(8)}),
        ])
      }catch(err) {console.log('Error', err)
      }

    }

    PromiseAll()

同样,也能够应用 try…catch 包裹着,来捕捉异样

正文完
 0