Function returning before async method done Node JS

后端 未结 3 542
长情又很酷
长情又很酷 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

    You can't return from an async function, you use a callback:

    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);
            }
        });
    };
    
    Api.getUser(req, result, function(user) {
        console.log(user);
    });
    

提交回复
热议问题