简体   繁体   中英

JavaScript : Open the first link from the list, wait and then open the next link

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")
}

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM