Function returning before async method done Node JS

后端 未结 3 541
长情又很酷
长情又很酷 2021-01-21 02:15

I currently have a function that is called from my router:

router.js:

var result = Api.getUser();

console.log(\"Result: \" + result);

3条回答
  •  太阳男子
    2021-01-21 02:44

    Promises are awesome, I would suggest looking into them. However, a simple callback will do the trick

    api:

    exports.getUser = function(req, result, callback) {
      request.get({
        uri: URL + '/user/me/',
        headers: {Authorization: 'bearer ' + req.user.accessToken},
        json: true
      }, function(e, r, body) {
            if(e) {
                callback({error: true});
            } else {
                callback(body)
            }
        });
    };
    

    router:

    var result
    Api.getUser(req, result, function (response) {
      result = response
      console.log(result)
    });
    

提交回复
热议问题