Return-1
Return-1

Reputation: 2449

Viewing objects in javascript ( under the hood )

Im very curious as to how objects are displayed in nodejs and in this case promises. When using console.log(promiseObject) the output is of type

{state:pending}

This seems very weird to me since a function .then() is invoked on that object so i would expect to see that there.

Try for yourself with this code

 function a(){

    var deferred = q.defer();

    setTimeout(function(){
        deferred.resolve();
    },4000)

    return deferred.promise;
}

var p1 = a()
console.log(p1) 
//outputs {state:pending} while i was expecting something like
//while i was expecting it to be {state:pending,then:function()}

Feels very arcane to me. I've also had similar problems in printing objects in the browser, seems like some fields are.. hidden? ( though i know of no such thing in javascript )

Upvotes: 0

Views: 181

Answers (2)

Shanoor
Shanoor

Reputation: 13662

Use a debugger, your browser has probably a good one. F12 in your browser and click the Run button below and you can explore a Promise object (works in Chrome/Chromium, Edge, Firefox):

console.clear();
var a = new Promise(function(res, rej) { res(); });
console.dir(a);

then(), catch() and other functions are in the __proto__ property.

Upvotes: 1

FastTurtle
FastTurtle

Reputation: 1777

var p1 = a()
console.log(p1)

here p1 is calling a function which returns a promise. so when you console log that promise you will see the status of promise. But you want the object do something like

function a(){

var deferred = q.defer();

setTimeout(function(){
    var data = {status: 'resolved', value: '3'};
    deferred.resolve(data);
},4000)

return deferred.promise;
}

a().then(function (data) {
  console.log(data); //prints {status: 'resolved', value: '3'}
}

hope it helped

Upvotes: 0

Related Questions