0

I have a list of divs I am iterating through. I think I figured it out using async/await:

let list = document.querySelectorAll('div')

async function goThrough() {
   for (let x = 0; x < list.length; x++) {
     let foo= await new Promise(resolve => {
        setTimeout(() => {
          console.log(x)
          resolve();
        }, 5000)
     });
   }
}

goThrough();

This seems to be logging each div node in the list with 5 seconds between them. I can't figure out how to do this using straight Promises though, without the luxury of async/await. I'm fine using async/await but curiosity has gotten the better of me and just trying to break it down to see if I can do it without it.

3 Answers 3

1

You could use recursion and call each promise only after the previous one was completed.

function goThrough(index, total) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(index), 1000);
  }).then((result) => {
    console.log(result);
    if (index + 1 < total) {
      goThrough(index + 1, total);
    }
  });
}

const list = document.querySelectorAll("div");
goThrough(0, list.length);
Sign up to request clarification or add additional context in comments.

Comments

0

You could go through the list recursively, no need to use Promises:

const list = [1, 2, 3, 4, 5, 6];

function goThrough(list, iList = 0) {
  if (iList >= list.length) {
    return;
  }
  setTimeout(() => {
    console.log(`list[${iList}] = ${list[iList]}`);
    goThrough(list, iList + 1);
  }, 5000);
}

goThrough(list);

Comments

0

A better way is to use list for what it already is - an iterable. The example below uses iter-ops library:

import {pipeAsync, delay} from 'iter-ops';

const i = pipeAsync(list, delay(1000)); //=> AsyncIterable

// testing:
(async function() {
    for await(const a of i) {
        console.log(a); // each value delayed by 1s
    }
})();

And you can iterate through the async result without asyc/await, if that's what you really want, though it's just needlessly awkward.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.