B
B
batman1012021-02-13 16:07:51
JavaScript
batman101, 2021-02-13 16:07:51

How does Promise.resolve work in Javascript?

Good afternoon everyone. Recently I came across one piece of code that I do not quite understand. I have a good understanding of what promises are and how working with them is made easier by async/await. For example, in the following code, no questions arise:

const func = async () => {
  return 100;
};

func()
  .then( res => {
    console.log(res);
    return 200;
  })
  .then( res => {
    console.log(res);
  });

/**
 * Expected output:
 * 100
 * 200
 */

However, in the following example it is not clear what should be in the function func:
const func = async () => {
  /** ??? */
};

func()
  .then( res => {
    console.log(res);
    return 200;
  })
  .then( res => {
    console.log(res);
  })
  .resolve(100);

/**
 * Expected output:
 * 100
 * 200
 */

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2021-02-13
@batman101

const deferred = () => {
  Promise.prototype.resolve = () => {}; // чтобы не было ошибок )
  return Promise.resolve("web");
}

"Normal" solution:
// проверка
deferred()
  .then(function(res) {
    console.log(200, res);
    return "lab";
  })
  .then(function(res) {
    console.log(100, res);
  })
  .resolve("web");

// реализация
function deferred() {
  function Box() {
    this.queue = [];
  }

  Box.prototype.then = function(func) {
    this.queue.push(func);
    return this;
  }

  Box.prototype.resolve = function(first_arg) {
    let arg = first_arg;
    while (this.queue.length)
      arg = this.queue.shift().call(this, arg);
  }

  return new Box;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question