vue中的async和await的使用介绍

使用promise处理回调地狱:

new Promise(resolve => {
          setTimeout(() => {
            resolve(hello)
          }, 2000)
        })
        .then(val => {
          console.log(123); 
          console.log(val) //  这一个then针对的是第一个promise,打印的是2秒后,返回的值hello
          return new Promise(resolve => { 
            setTimeout(() => {
              resolve(world)
            }, 2000)
          })
        })
        .then(val => {
          console.log(456);
          console.log(val) // 这个then针对的是第一个then,返回的promise,四秒后后 打印上一个.then 返回的值 world
        }),

先说一下async的用法,它作为一个关键字放到函数前面,用于表示函数是一个异步函数,因为async就是异步的意思, 异步函数也就意味着该函数的执行不会阻塞后面代码的执行。

定义一个async方法:

async function sayHello() { // 定义一个async(异步)方法,
      return hello world // 返回一个值
    }
    // console.log(sayHello()); 
    // 打印的是promise对象:Promise{<fulfilled>: hello world}
    // 因为是个promise对象,则需要使用.then获取promise的返回值
 
    sayHello().then(res=>{
      console.log(res);
    })
    console.log(123);
    // 以上打印的顺序:先打印 123   再打印 hello world
  }

异步函数返回成功和失败的操作:

// 异步函数返回成功和失败的操作
      async function timeout(flag) {
        if (flag) {
            return hello world
        } else {
            throw my god, failure
        }
    }
      timeout(true).then(res=>{ // 成功  使用then获取成功的值
        console.log(res);  //hello world
      })
      timeout(false).catch(res=>{  // 失败 使用catch 获取抛错后的值
        console.log(res); // my god, failure
      })
      console.log(timeout(true))  // Promise{<fulfilled>: hello world} 调用Promise.resolve() 返回promise 对象。
      console.log(timeout(false)); // Promise{<rejected>: my god, failure} 调用Promise.reject() 返回promise 对象。
    }

await关键字:注意await关键字只能放到async函数里面

// 2s 之后返回双倍的值
        function doubleAfter2seconds(num) { // 定以一个方法,返回一个promise方法
            return new Promise((resolve, reject) => {
              console.log(resolve, reject)
                setTimeout(() => { // 一个倒计时计时器
                    resolve(2 * num)
                }, 2000);
            } )
        }
        async function testResult() { // 声明一个async方法,async
            console.log(123123);
            let result = await doubleAfter2seconds(30); // await 在async后面使用,表示等待后面这个方法执行
            console.log(456456);
            console.log(result);
        }
        
        testResult();

        // 上面先打印 123123,两秒钟后,打印456456,接着就是await等待的这个方法返回的值

转载自:

经验分享 程序员 微信小程序 职场和发展