微信小程序-了解async、await、promise

1、async是什么

  async用于声明异步的,常常用于处理回调函数。

  async返回一个promise的对象,可以直接用.then,.catch来处理结果。
  onLoad: function (options) {
    // 声明该方法为异步方法,会返回一个Promise对象
    async function test(){
      return '云开发'
    }
    // var a = test();
    // console.log(a)
    console.log(test())
    test().then((res)=>{
      console.log("ook")
    })
    test().catch(err=>{
      console.log('nono')
    })
  }




2、resolve成功之后的返回, reject是失败的返回。


3、await 它会阻止后面的代码运行,因为他后面的代码会等待上一个await完成(resolve)
  await避免产生了回调地狱情况,并且提高了代码的可读性。
  注意:await需要搭配async使用,否则会报错。
 
  当没有使用await时,会直接返回Promise对象,并不会执行完resolve()内容。
  function pro1() {
      return new Promise((resolve, reject) => {
        resolve(1)
      })
    }

    function pro2() {
      return new Promise((resolve, reject) => {
        resolve(2)
      })
    }


    // 不使用await
    const a1 = pro1()
    const a2 = pro2()
    console.log(a1)
    console.log(a2)

执行结果:

 
使用await时:
    function pro1() {
      return new Promise((resolve, reject) => {
        //延时4秒
        setTimeout(()=>{
          resolve(1)
        },4000)
      })
    }

    function pro2() {
      return new Promise((resolve, reject) => {
        resolve(2)
      })
    }

    async function test2(){
      const a1 = await pro1()
      const a2 = await pro2()
      console.log(a1)
      console.log(a2)
    }
    test2()

执行结果:因为await会阻止后面的代码运行,因为他会面的代码会等待上一个await完成,也就是会执行完resolve()再结束方法。

 

4、云函数中的async和await

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  var page = await new Promise((resolve,reject)=>{
    setTimeout(()=>{
      resolve(event.a+event.b)
    },2000)
  })
  return page
}

 

 
posted @ 2021-01-08 23:22  RainstormDy  阅读(1646)  评论(0)    收藏  举报