0

I am learning about the JavaScript async / await API, and implementing the example code from MDN.

In one section, detailing the differences between async/await and promise.then(), the following is written:

var resolveAfter2Seconds = function() {
  console.log("starting slow promise");
  return new Promise(resolve => {
    setTimeout(function() {
      resolve(20);
      console.log("slow promise is done");
    }, 2000);
  });
};

var parallel = function() {
  console.log('==PARALLEL with Promise.then==');
  resolveAfter2Seconds().then((message)=>console.log(message)); 
  // in this case could be simply written as console.log(resolveAfter2Seconds());

}

setTimeout(parallel, 10000); 

I was suspicious about the bit that says

// in this case could be simply written as console.log(resolveAfter2Seconds())

So, I ran the code and got the following:

starting slow promise
Promise { <pending> }
slow promise is done

Is the MDN example code comment trying to imply that instead of Promise { <pending> }, I should see 20? Why?

Caleb Jay
  • 2,159
  • 3
  • 32
  • 66
  • 1
    The example code comment looks completely wrong. – Jacob Oct 23 '18 at 19:03
  • 2
    This looks like a typo in the docs - could potentially write `console.log(await resolveAfter2Seconds())` - you should make a change request – Michael Oct 23 '18 at 19:04
  • @Michael that'd be exciting, but I'm not sure that code works. I tried `console.log( await resolveAfter2Seconds());` and got `SyntaxError: missing ) after argument list` – Caleb Jay Oct 23 '18 at 19:07
  • @CalebJay: you can only `await` inside of an `async function`. – Jacob Oct 23 '18 at 19:12
  • @Jacob oh right, and my previous version of this comment was me missing another syntax error; This works: `var trythis = async function(){ console.log(await resolveAfter2Seconds()); } trythis();` – Caleb Jay Oct 23 '18 at 19:14
  • Yeah, that page doesn't look good. They also don't show an example of `await Promise.all(…)` and feature the [concurrent-`await`s antipattern](https://stackoverflow.com/questions/46889290/waiting-for-more-than-one-concurrent-await-operation). – Bergi Oct 23 '18 at 19:21
  • you could do this: `.then(console.log)` – Sumi Straessle Oct 23 '18 at 20:50

0 Answers0