Viewing objects in javascript ( under the hood )

二次信任 提交于 2019-12-12 01:38:42

问题


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 )


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/35912540/viewing-objects-in-javascript-under-the-hood

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!