求教 promise怎么用
发布于 6 年前 作者 ylu 17633 次浏览 来自 问答

直接写上我的部分代码和我期待的效果,请各路大神帮忙解答下

function(){

   var bl = this.openLogin()

   //因为是wx.request是异步 ,所以这里的bl还没有赋值  请问我该怎么写?

    if (bl) {

        

   } else {

 

   }

}

openLogin:function(){

   var _this = this;

   wx.request({

       url: getApp().globalData.ctPath,

       data: {

           wxOpenid: _this.globalData.openid

       },

       header: getApp().globalData.header,

       success: function (res) {

           if (res.data.user != null) {

               return true;

           }else{

               return false;

           }

       }

   })

}

5 回复

这是修改后的代码,你试试


openLogin:function(){

   var _this = this;

const demo= new  Promise((resolve, reject) => {

   wx.request({

       url: getApp().globalData.ctPath,

       data: {

           wxOpenid: _this.globalData.openid

       },

       header: getApp().globalData.header,

       success: function (res) {

            resolve(res)

       }

   })

})

demo.then(res=>{

           if (res.data.user != null) {

               return true;

           }else{

               return false;

           }

})

}

那个是异步的吧,不能直接把 openLogin() 返回值赋给 bl 的,感觉写这个 Promise 貌似没什么用啊 😂 你在 success 回调里调用你下一步操作的函数好了

引入es6-promise,然后使用promise,小程序原生不支持promise

使用es6语法

wechatide://minicode/BVKBEHmB7YV7

回到顶部