The JS callback function is not valid for variable assignment

A strange phenomenon occurred when developing WeChat Mini Programs .
reference code is as follows:

//
var userName,portrait;
wx.getUserInfo({
    success: function (res) {
        var userInfo=res.userInfo;
        //wx.getUserInfo
        userName=userInfo.nickName;
        portrait=userInfo.avatarUrl;
    }
});
this.database.collection("Comment").add({
    data: {
        //:
        userName: userName,
        portrait: portrait
    }
});

has annotated the problem points in the code, and the
editor prompts Variable might not have been initialized,
why the variable assignment is not valid in the callback function? How to solve?

Whether
wx.getUserInfo is asynchronous userName or undefined


when success callback occurs, calling the save function


can be understood as Synchronize async. Wx.getUserInfo assigns values to global variables asynchronously. The value of the global variable when the this.database.collection is executed is the same as it was at the time of initialization (the global variable is declared not to be initialized, that is, undefined).

Menu