Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a returned Promise not have a method on it .then when logged to the console?

I understand that a new promise has a .then method on it.

But when I console log the promise returned from getUserData('jeresig') I get this object logged to the console (with no .then method).

Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }

Is .then actually on the new promise object or perhaps it only gets added to the object later asynchronously?

So does that mean .then is called asynchronously even though it looks synchronous?

let Promise = require('bluebird'),
    GitHubApi = require('github'),

let github = new GitHubApi({
  version: '3.0.0'
});

function getUserData (user){
    return new Promise(function(resolve, reject){
      github.user.getFollowingFromUser({
        user: user,
        per_page: 2
      }, function(err, res){
        if (err){ reject(err) }
        else {
          resolve(res)
        }
      })
    })
}

console.log(getUserData('jeresig'))

  // .then(function(data){
  //   console.log('data', data)
  // })
  // .catch(function(error){
  //   console.log('error', error)
  // })
like image 248
michaelbamberger Avatar asked Dec 05 '25 09:12

michaelbamberger


1 Answers

The .then() handler is already there. This is just an issue with what you're looking at in the console.

It's on the prototype of the object which is not shown by default in console.log(). Since it looks like you are looking at a Bluebird promise, if you look at the returned promise in the console in Chrome, you can expand the object in the console and see everything that is on the promise object, including the methods on the prototype. .then() is there from the moment the promise is created.

You can also see for sure that it's there by doing this:

var p = getUserData('jeresig');
console.log(p.then);

And, .then() has to be there initially or the whole concept of the promise will not work because you call .then() on it synchronously. That's how you register your interest in knowing when the promise is resolved in the future.

like image 78
jfriend00 Avatar answered Dec 06 '25 23:12

jfriend00