@Mishytca

Как запустить Promis-ы последовательно?

Имеется вот такой Promise:

const p = new Promise((resolve, reject)=>{        
        setTimeout(() => {
            console.log ("Первый выполнен");
            resolve();
        }, 2000);
    });

    p.then(()=>{         
        setTimeout(() => {
            console.log ("Второй выполнен");
          }, 1000);
    });

Результат:

Первый выполнен
Второй выполнен


А как я могу сделать, чтобы Promise работал "по кругу"?
Желаемый результат:
Первый выполнен
Второй выполнен
Первый выполнен
Второй выполнен

И так далее...
  • Вопрос задан
  • 120 просмотров
Решения вопроса 1
Seasle
@Seasle Куратор тега JavaScript
const createPromiseLoop = promises => {
  let index = 0;
  
  const attach = (...args) => {
    promises[index++](...args)
      .then((...args) => attach(...args));
    
    index %= promises.length;
  };
  
  return (...args) => {
    attach(...args);
  };
};

const sleep = (duration = 0) => new Promise(resolve => setTimeout(resolve, duration));

const loop = createPromiseLoop([
  (number) => new Promise(async resolve => {
    await sleep(100);
    console.log(`Number plus one. Received: ${number}`);
    resolve(number + 1);
  }),
  (number) => new Promise(async resolve => {
    await sleep(100);
    console.log(`Number multiply two. Received: ${number}`);
    resolve(number * 2);
  }),
]);

loop(1);
/*
'Number plus one. Received: 1'
'Number multiply two. Received: 2'
'Number plus one. Received: 4'
'Number multiply two. Received: 5'
'Number plus one. Received: 10'
'Number multiply two. Received: 11'
'Number plus one. Received: 22'
'Number multiply two. Received: 23'
'Number plus one. Received: 46'
'Number multiply two. Received: 47'
'Number plus one. Received: 94'
'Number multiply two. Received: 95'
'Number plus one. Received: 190'
'Number multiply two. Received: 191'
'Number plus one. Received: 382'
'Number multiply two. Received: 383'
'Number plus one. Received: 766'
'Number multiply two. Received: 767'
'Number plus one. Received: 1534'
'Number multiply two. Received: 1535'
'Number plus one. Received: 3070'
'Number multiply two. Received: 3071'
'Number plus one. Received: 6142'
'Number multiply two. Received: 6143'
'Number plus one. Received: 12286'
'Number multiply two. Received: 12287'
'Number plus one. Received: 24574'
*/

И код никогда не остановится.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

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

Похожие вопросы