-3

This is sample code from here

function resolveAfter2Seconds(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}

async function f1() {
  var x = await resolveAfter2Seconds(10);
  console.log(x); // 10
}

f1();

I have few questions:

  1. What is the resolve in the Promise constructor, and what resolve(x) do exactly?
  2. What is asynchronous code? is it the call to resolveAfter2Seconds or just the code inside resolveAfter2Seconds (that is: the promise execution, while resolveAfter2Seconds returns immediately?
VLAZ
  • 26,331
  • 9
  • 49
  • 67
OJNSim
  • 736
  • 1
  • 6
  • 22
  • It logs "10" to the console. The basics are best to learn from tutorials and documentations, see ex. https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Concepts and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise – Teemu Jun 16 '21 at 17:27
  • @Teemu that I know and see. My questions are about the way this code works – OJNSim Jun 16 '21 at 17:29
  • But that's what you've asked in the title ; ). I've updated my comment. – Teemu Jun 16 '21 at 17:30
  • @VLAZ You have an excellent answer for how async/await works, a dup target. I've bookmarked it, but currently not on that machine ... – Teemu Jun 16 '21 at 17:37
  • @Teemu I do? Completely honestly, I can't remember. I recall answering about some of the slightly weirder async stuff like [why assigning to a variable vs a single expression behaves differently](https://stackoverflow.com/a/58614717/) but I'm not sure I've gone in detail about what OP is asking here - namely the executor function. I'm trying to find a dupe target for that. – VLAZ Jun 16 '21 at 17:45
  • @VLAZ I asked you to add an explanation of what blocking means, and you added it. Last autumn/winter ... – Teemu Jun 16 '21 at 17:48
  • OK...I'll try to find something, in my answers about that. – VLAZ Jun 16 '21 at 17:50
  • @Teemu I understand `resolve` is somehow a function or supposed to be a function aka _executor function_, isn't it? but this function is not define. Also another thing I do not understand, can a promise be used on the server side, or is it only a client side ability? – OJNSim Jun 16 '21 at 17:50
  • @OJNSim That might be a bit confusing, but the lines after the `await` line in `f1` is the `resolve` function. Promises are available in the latest Node.js versions too. – Teemu Jun 16 '21 at 18:04
  • @VLAZ Found it: https://stackoverflow.com/a/65836893/1169519 – Teemu Jun 16 '21 at 18:11
  • @Teemu ah, I see! Great. However, it doesn't cover promise executors. I can't find a good dupe target for those - they are discussed in some detail in a few questions. – VLAZ Jun 16 '21 at 18:17
  • It's a bit ironic, that `async` and `await` were added to JS to make promises easier to understand and use. The concept hits the target when awaiting asynchronous native/library functions, but misses the target badly when a developer has to create the promise to await by himself. – Teemu Jun 16 '21 at 18:23

1 Answers1

1
  1. What is the resolve in the Promise constructor, and what resolve(x) do exactly?

The Promise constructor takes a callback function called executor. That executor callback will be called with two parameters. This call is made by the constructor itself. Both of parameters that will be passed in are functions:

  1. resolve - when called will fulfill* the promise, marking it as successfully completed. The argument passed to the resolve function will become the value for that promise.

    The value for the promise will be passed to .then() callback. If the promise is awaited the result is the value of the promise.

  2. reject - when called will reject the promise, marking it as unsuccessfully completed. The argument passed to the reject function will become the reason that promise was rejected.

    The reason for the rejection will be passed to .catch() callback. If the promise is awaited the reason is thrown and can be caught in a try/catch block.

Quick note: as with all parameters, these two can be given any name. The resolve and reject are very common ways of naming the functions.

* not necessarily true if passing another promise. If a another promise is passed, the current promise will adopt that promise's completion state. So, if resolve is called with a promise that is later rejected, the current promise will also be rejected.


The executor is then called immediately and the promise will be pending until either resolve or reject is called.

In your case the executor is:

resolve => {
  setTimeout(() => {
    resolve(x);
  }, 2000);
}

Which means that resolve is going to be called 2 seconds later with the value for x making that the value for the promise.

The await will suspend the execution of f1() and resume it when promise returned by resolveAfter2Seconds(10) settles. The result of await resolveAfter2Seconds(10) is the value of the promise. Which is 10 as you can see in the log.


  1. What is asynchronous code? is it the call to resolveAfter2Seconds or just the code inside resolveAfter2Seconds (that is: the promise execution, while resolveAfter2Seconds returns immediately?

I would say that for practical purposes, asynchronous code is anything that will finish later than the normal top-to-bottom execution of code:

console.log(1);
console.log(2);
console.log(3);

async function later(x) { return x; }

console.log(1);
later(2).then(value => console.log(value));
console.log(3);

You could definitely try to make an argument otherwise, however trying to pinpoint exactly where async code starts and ends is not very useful. It runs the risk of turning into something that resembles Sorites paradox. If fn1 is not async code, then is it calling fn2 which lies inside? Or is it fn3 which is inside fn2? Etc. Hence my proposed more practical solution. If a function causes some effect to come up later than the current run-to-completion cycle we can say that it is asynchronous. So, any function that returns a promise (which includes all async functions) are asynchronous.

You can also see my answer here which discusses various asynchronous functions more.


Further reading:

What is the correct terminology for javascript promises - very important as it explains the fundamental concept of promises.
`resolve` and `reject` functions inside a Promise's executor How is a promise/defer library implemented?
Concept - Distilling how a promise works?

VLAZ
  • 26,331
  • 9
  • 49
  • 67