DarthJS
@DarthJS

Как правильно дождаться результата асинхронных функций в цепочке вызовов?

Например есть конструктор:
function Foo () {
this.results = [];
}

//
Foo.prototype.tick = function (callback) {
callback(function (data) {
Promise.resolve(this.results.push(data));
});
return this;
}

Foo.prototype.finish = function () {

this.wait().then(function (response) {
console.log(response) // second, first
})
}

//
function callBackFooFirst (cb) {

setTimeour(cb, 4000, 'first')
}

function callBackFooSecond (cb) {

setTimeour(cb, 1000, 'second')
}

// И собственно вызов
var test = new Foo();

test
.tick(callBackFooFirst)
.tick(callBackFooSecond)
  • Вопрос задан
  • 68 просмотров
Решения вопроса 1
rockon404
@rockon404
Frontend Developer
Можно так:
class Foo {
  constructor() {
    this.queue = [];
  }

  tick(cb) {
    this.queue.push(cb);
    return this;
  }

  then(cb) {
    return this.queue.reduce((acc, fn) =>
      acc.then(fn), Promise.resolve()).then(cb);
  }
}


Вариант в прототипном стиле:
function Foo() {
  this.queue = [];
}

Foo.prototype.tick = function(cb) {
  this.queue.push(cb);
  return this;
}

Foo.prototype.then = function(cb) {
  return this.queue.reduce(function(acc, fn) {
    return acc.then(fn);
  }, Promise.resolve()).then(cb);
}


Пример использования:
const foo = new Foo();

const task1 = () =>
  new Promise(resolve => {
    setTimeout(() => {
      console.log('task1');
      resolve('Done!');
    }, 1000);
  });

const task2 = arg =>
  new Promise(resolve => {
    setTimeout(() => {
      console.log('task2');
      resolve(arg);
    }, 1000);
  });

foo.tick(task1)
   .tick(task2)
   .then(console.log);

/* result:

    task1
    task2
    Done!

*/
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

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

Войти через центр авторизации
Похожие вопросы
19 апр. 2024, в 03:52
1000 руб./за проект
19 апр. 2024, в 03:01
1000 руб./за проект
18 апр. 2024, в 21:56
2000 руб./за проект