-1

I'm new to Promise's and I'm trying to wrap my head around getting the value.

Here's an idea of what I'm trying to do:

API = {
  get: function() {
    return new Promise(function(res) {
      setTimeout(function() {
        res('foo')
      }, 1000)
    })
  }
}

var foo = API.get()

console.log(foo)

It's important that var foo = API.get() remains as it is.

Any idea what to do here?

daryl
  • 14,307
  • 21
  • 67
  • 92
  • 1
    Nothing. What you want is impossible. I recommend to read http://www.html5rocks.com/en/tutorials/es6/promises/ to learn how promises work. – Felix Kling Dec 15 '14 at 14:36
  • This question appears to be off-topic because it is about a fundamental misunderstanding of asynchronicity. –  Dec 15 '14 at 19:01

2 Answers2

3

Promises are still asynchronous. You still can't inspect their value in synchronous code.

You need:

API.get().then(function(result) {
    // Resolved value from the Promise object returned by API.get()
    console.log(result);
});

API.get() returns a promise object, you then invoke the .then() method on that object.

Another more verbose way would be:

var fooPromise = API.get();
fooPromise.then(function(result) { 
    console.log(result); 
});
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
0

Promises are about something happening in the future; you cannot examine their eventual values now unless you are in possession of a time machine.

I am not suggesting you do this, but merely for didactic purposes, if you really want your code to function as you seem to, you could redefine console.log to be promise-aware:

console.log = function() {
    var old_console_dot_log = console.log.bind(console);
    return function(maybe_promise) {
        Promise.resolve(maybe_promise).then(old_console_dot_log);
    };
}();

(This version only handles one argument; handling more is left as an exercise.)

Now when you say console.log(foo), it will log the resolved value of foo, but only when it is good and ready, one second from now.

  • I don't understand why this was downvoted. While I think this answer can be improved (in the tone and somewhat in the content) I don't see anything here deserving of a downvote and the log trick is clever since it even preserves order - downvoter - care to explain why? – Benjamin Gruenbaum Dec 15 '14 at 18:23
  • Because I thought it was common sense that the `console.log` in the code snippet was merely there just to log the value of the variable `foo`, I'm not looking to override `console.log` are you guys for real. – daryl Dec 15 '14 at 18:40
  • 1
    @darylm. it's a "what you want is impossible" (which is is) + "thinking outside the box". You got the hard cold truth first I don't understand why you downvoted it. – Benjamin Gruenbaum Dec 15 '14 at 19:19
  • @daryl What you want is impossible. Your program can't see into the future. – Madara's Ghost Dec 16 '14 at 08:51