Promise returns undefined

2019-01-26 20:28发布

问题:

I know you can't make an asynchronous function behave synchronously but how do I add some kind of order to my promises chain?

One result relies on the previous promise value and when that doesn't happen I get an undefined error. It's an http request so it is relying on external factors like how fast my connection can execute the request, etc.

module.exports.movieCheck = function(authToken) {
return request({
    method : 'GET',
    uri : 'https://graph.facebook.com/' + profileID + '/posts?fields=message&limit=25&' + authToken
    }).spread(function (response, body) {
        console.log('https://graph.facebook.com/' + profileID + '/posts?fields=message&limit=25&' + authToken);
        return body;
    }, function(e) {
        console.log(e);
});
};

I am calling the above method as follows. However console.log returns undefined.

movieCheck.getToken()
.then(function(token) {
  movieCheck.movieCheck(token);
})
.then(function(movies) {
  console.log(movies); //should print json data
});   

Terminal prints

undefined
https://graph.facebook.com/.../posts?fields=message&limit=25&access_token=....

回答1:

Try to return the promise from the first then callback

movieCheck.getToken()
    .then(function (token) {
    return movieCheck.movieCheck(token);
}).then(function (movies) {
    console.log(movies); //should print json data
});