1

I'm trying to open each link from the below list and trying to do some action once the page loads.

The flow should be like,

  • open the link
  • do the some action
  • open the next link from the list
  • do the some action
  • move to the next link from the list

I have the below code. Instead of opening the first link, it directly jumps to second link and performs the action. I'm not very bright with Js Async.

Much appreciate your help on this!

let lst = ["https://twitter.com/pinsky", "https://twitter.com/adamiqshan"]

lst.forEach( link => {
    setTimeout(openLink(link), 5000)
})

function openLink(URL){
    window.open(URL, "_self")
}
1
  • 2
    quick comment regarding your use of setTimeout - the first parameter should be a function, so your code should say setTimeout(() => openLink(link), 5000). But Marc's answer below using Promises is a cleaner way to handle this situation. Commented Oct 2, 2020 at 20:35

1 Answer 1

5

Wrap your work code in a promise. If your done with your work, resolve the promise.

Build out of that a promise chain/stack and execute it.

let lst = ["https://twitter.com/pinsky", "https://twitter.com/adamiqshan"]

let wrapper = lst.map((url) => {
  return () => {    
      return new Promise((resolve) => {
        
        // do your work here
        // when your are done, call resolve()
        // so the next url will be proceeded
        console.log("proceed", url);
        setTimeout(resolve, 5000);
        
      });    
  };
});


// create promise stack
wrapper.reduce((prev, cur) => {  
   return prev.then(cur);
}, Promise.resolve());

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.