@batman101

Как работает Promise.resolve в Javascript?

Всем добрый день. Недавно встретил один кусок кода, который не совсем понимаю. Я имею хорошее представление о том, что такое промисы и как работа с ними упрощается благодаря async/await. Например, в следующем коде вопросов никаких не возникает:
const func = async () => {
  return 100;
};

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

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

Однако в следующем примере непонятно, что должно быть в функции func:
const func = async () => {
  /** ??? */
};

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

/**
 * Expected output:
 * 100
 * 200
 */
  • Вопрос задан
  • 190 просмотров
Решения вопроса 1
sergiks
@sergiks Куратор тега JavaScript
♬♬
const deferred = () => {
  Promise.prototype.resolve = () => {}; // чтобы не было ошибок )
  return Promise.resolve("web");
}


«Нормальное» решение:
// проверка
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;
}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы