Add timer to Promise.all, map

蓝咒 提交于 2021-01-05 07:25:25

问题


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.


回答1:


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;
}



回答2:


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


来源:https://stackoverflow.com/questions/48093956/add-timer-to-promise-all-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!