Mini Program uses promise across files

how to use chained calls to promise when encountering asynchronous code across files?

I now write WeChat Mini Programs, calling wx.login,wx.getUserInfo in app.js and returning token and uid interfaces from my server.
but in a subpage, you need to get the uid returned in app.js before you can request the request of the current page again. Because it is cross-file, how to write this string of chained calls to promise?


var app=getApp ();
console.info (app.uid,app.token);


is it similar to this that only one call is made and all other calls are cached

var getUid = (function(){
    var uid = null;
    var flag = true;
    var p = null;
    return function(){
        if(!uid){
            if(flag){
                flag = false;
                //
                p = new Promise(function(resolve){
                    setTimeout(function(){
                        resolve(uid=123);
                    },2000)
                })
            }
            return p
        }else{
            return Promise.resolve(uid);
        }
    }
}());

getUid().then(function(v){
  console.log(v)//2  123
})

getUid().then(function(v){
  console.log(v)//2  123
})

setTimeout(function(){
  getUid().then(function(v){
    console.log(v)//5  123
  })
},5000)

event notification mechanism can be used. In your case, publish / subscribe mode is suitable.

you can refer to this article: https://aotu.io/notes/2017/01.


take the uid should be an asynchronous, package a promise, and then execute request


how to solve this problem

Menu