Function returning before async method done Node JS

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

    You are dealing with asynchronous code. There are a couple ways to solve this problem.

    With A Promise

    // api.js
    var Promise = require('bluebird');
    var request = require('request');
    var getP = Promise.promisify(request.get.bind(request));
    
    exports.getUser = function(accessToken) {
      return getP({
        uri: URL + '/user/me/',
        headers: {Authorization: 'bearer ' + accessToken},
        json: true
      }).spread(function(e, r, body) {
        console.log("e: " + e + " body: %j", body);
        if(e) {
          return Promise.reject("{error: true}");
        } else {
          return Promise.resolve(body);
        }
      });
    };
    
    // main.js
    api.getUser(req.user.accessToken)
      .then(console.log.bind(console, "Result: "))
      .catch(console.error.bind(console));
    

    With A Callback

    // api.js
    var request = require('request');
    
    exports.getUser = function(accessToken, callback) {
      request.get({
        uri: URL + '/user/me/',
        headers: {Authorization: 'bearer ' + accessToken},
        json: true
      }, function(e, r, body) {
        console.log("e: " + e + " body: %j", body);
        if(e) {
          callback("{error: true}");
        } else {
          callback(null, body);
        }
      });
    };
    
    // main.js
    api.getUser(req.user.accessToken, function (err, result) {
      if (err) return console.error(err);
      console.log("Result: " + result);
    });
    

    The nice thing about the promise API is that you only ever need to check for errors once, in your final .catch handler. In the callback style if you need to keep making additional asynchronous calls then you'll have to keep nesting callbacks and checking if (err) return console.error(err) in every single callback.

提交回复
热议问题