简体   繁体   中英

Add timer to Promise.all, map

I would like to add some timeout between below get requests. I mean, flow should be looks like: timeout, https://example.com/example1, timeout, https://example.com/example2, timeout, https://example.com/example3, timeout etc. (or without first timeout, whatever).

Below function is working properly:

function promiseGetInformationFromMultipleUrls(parts) {
    return Promise.all(parts.map(part => {
      return request({
            'url': `https://example.com/${part}`,
            'json': true
        }).then(partData =>  {console.log("Part data was fetched: " + part); return partData.result;})
          .catch(err => {console.error("Error during fetching data from part: " + part + ", error code: " + err.statusCode);});
    }));
}

Where parts is -> example1, example2, example3....

I am trying do it by adding timer:

const timer = ms => new Promise( res => setTimeout(res, ms));

And use it:

function promiseGetInformationFromMultipleUrls(parts) {
    return Promise.all(parts.map(part => {
    console.log("wait 1 seconds");
    timer(1000).then(_=>console.log("done"));
      return request({
            'url': `https://example.com/${part}`,
            'json': true
        }).then(partData =>  {console.log("Part data was fetched: " + part); return partData.result;})
          .catch(err => {console.error("Error during fetching data from part: " + part + ", error code: " + err.statusCode);});
    }));
}

But it is wrong flow -> timeout, timeout, timeout,..., get request1, get request 2, get request 3 .

You may reduce it to a Promise chain:

function promiseGetInformationFromMultipleUrls(parts) {
 return parts.reduce((chain, part) =>
  chain.then((result) =>
    timer(1000).then(() => 
      request(/*...*/).then(res => 
        result.concat(res)
      )
    )
  ),
  Promise.resolve([])
);
}

However thats quite ugly, so you may use async / await instead:

 async function promiseGetInformationFromMultipleUrls(parts){
   const result = [];
   for(const part of parts){
     await timer(1000);
     result.push(await request(/*...*/));
  }
  return result;
}

The following should work:

const Fail = function(reason){this.reason=reason;};
const isFail = x=>(x&&x.constructor)===Fail;
const timedoutPromise = time => promise => 
  Promise.race([
    promise,
    new Promise(
      (resolve,reject)=>
        setTimeout(
          x=>reject("timed out"),
          time
        )
    )
  ]);

utls = [];//array of urls
in5Seconds = timedoutPromise(5000);
Promise.all(
  urls.map(
    url=>
      in5Seconds(makeRequest(url))
      .catch(e=>new Fail([e,url]))//failed, add Fail type object
  )
)
.then(
  results=>{
    const successes = results.filter(x=!isFail(x));
    const failed = results.filter(isFail);
    const timedOut = failed.filter(([e])=>e==="timed out");
  }
)

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