Skip to content Skip to sidebar Skip to footer

How Javascript Promises Work Behind The Scenes

I'm so much confused about what happens behind the scenes when promise is produced and consume. Please clarify my points and sorry for my weak English. blank object is created wit

Solution 1:

The following is a simplified implementation of the built-in Promise class. catch and finally have not been implemented.

The function supplied to the Promise constructor is called the executor function, and is invoked immediately and synchronously.

Every promise has a method .then, enabling the chaining of promises.

Functions supplied to .thenare always invoked asynchronously on a microtask (note use of queueMicrotask below).

Every time .then is called, a new promise is created and returned.

.then can be called more than once on the same promise, creating a multicast of the result of the promise, and a branching of the promise chain.

A promise can be in one of three states: pending, fulfilled, or rejected. State transitions are unidirectional: you cannot move from fulfilled or rejected, back to pending.

If a promise is resolved with another promise, then the two promise chains are joined and the outer promise takes on the status of the inner promise (which could be pending), until the inner promise resolves.

functionPromise(executor) {
  if (!executor) throw"Promise executor undefined"let status = "pending", value, thenQ = []

  constthen = onFulfilled => {
    let resolver
    // This ensures control does not move to later promises // until prior promises have been resolved.const nextPromise = newPromise(resolve => (resolver = resolve))
    // More than one "then" can be registered with each promise.
    thenQ.push((...args) =>resolver(onFulfilled(...args)))
    return nextPromise
  }

  // We check if the result is a "thenable"; if so, we treat// it as an inner promise, otherwise we simply fulfil with // the result.constresolve = result => result?.then ? result.then(fulfil) : fulfil(result)

  // When a promise has been fulfilled, its "thens" can be run.constfulfil = result => (status = "fulfilled", value = result, executeThens(value))

  // "Thens" are run asynchronously, on a microtask.constexecuteThens = value => queueMicrotask(() => thenQ.forEach(el =>el(value)))

  // The executor is run synchronously.executor(resolve)

  return {
    then,
    getstatus() { return status },
    getvalue() { return value }
  }
}

// ChainingnewPromise(resolve => {
  console.log('Waiting for step 1...')
  setTimeout(() =>resolve("One, two..."), 1500)
})
.then(result =>newPromise(resolve => {
  console.log('Waiting for step 2...')
  setTimeout(() =>resolve(`${result}three, four`), 1500)
}))
.then(result =>console.log(`Chaining result: ${result}.`))

// Branchingconst p = newPromise(resolve => {
  console.log('Waiting for step a...')
  setTimeout(() =>resolve("Alpha, Bravo..."), 1500)
})

p.then(result =>newPromise(resolve => {
  console.log('Waiting for step b1...')
  setTimeout(() =>resolve(`${result}Charlie, Delta`), 1500)
})).then(console.log)

p.then(result => {
  console.log('Waiting for step b2...')
  return`${result}Echo, Foxtrot`
}).then(console.log)

See also.

Solution 2:

I'll go through your code in the order of execution.

At all times the value of this is whatever it was at the beginning. That's because you're only using arrow functions. But that's not relevant since you're not referencing this.

Main Code

let myPromise = new Promise(executor); creates a pending promise object. While creating the promise, the executor function will be executed.

setTimeout(callback, 1500); puts the callback function on some internal timer queue. The javascript engine promises to do its best to execute callback after (at least) 1500ms.

let a = 10; sets the variable a to 10.

myPromise.then(onFulfilled); creates another pending promise. It is linked to myPromise so that onFulfilled will be scheduled asynchronously when myPromise is fulfilled.

console.log(a); prints the value of a which is 10.

For the next 1500ms nothing happens. Then callback gets executed.

callback of setTimeout

console.log(getIDs); prints getIDs. From the name you can guess it's a function. So something like [Function: getIDs] will be printed.

resolve(10); fulfills myPromise and sets its result to 10. Since myPromised is now fulfilled, onFulfilled of anotherPromise gets scheduled asynchronously.

Now we have to wait for the call stack to process. After that, onFulfilled will be called.

onFulfilled of myPromise.then

console.log(val); prints the content of val. That is, the result of myPromise.

Post a Comment for "How Javascript Promises Work Behind The Scenes"