微信小程序Promise异步简化回调

Promise异步简化回调

使用的背景:同时存在两个或者多个网络请求,且第二个请求要使用第一个请求返回的数据

代码:

const app = getApp()

Page({
  data: {

  },
  onLoad: function () {
    this.function_1().then(res=>{
      console.log('方法1结果:',res)

      //这里可以把结果放到GetUserEntity_2作为参数
      this.function_2().then(res=>{
        console.log('方法2结果:',res)
      })

    }
    )
  },
  
  function_1() {
    return new Promise(function (resolve, reject) {

      // 这里的延时可以换为网络请求
      setTimeout(function () {
        let result = '服务器返回的结果11';
        resolve(result) ;

        // 失败时用reject返回
        // reject(result)

      }, 3000) //延时


    })     
  },

  function_2() {
    return new Promise(function (resolve, reject) {

      // 这里的延时可以换为网络请求
      setTimeout(function () {
        let result = '服务器返回的结果22';
        resolve(result) ;
      }, 3000) //延时

    })
  },


})

猜你喜欢

转载自blog.csdn.net/wy313622821/article/details/107464112