简体   繁体   中英

Pausing an endpoint until the promise returns a fulfilled promise

I'm trying to speed up an endpoint and I think have an idea on how to do it however I'm not totally sure if it is a possible or worth trying to figure out.

Essentially what I want to do is return a promise and then based on the status code 202 or 200 I will determine if the next request should be made or if it should be delayed with something like Promise.all(). The reason I want to try and do this is because using only setTimeout I can only get around a max of 50 request per second and I'm trying to push that to something closer to 200 request per second.

Current delay function for endpoint:

const delayQue = () =>{
    if(count % 25 == 0 && count > 0){
        setTimeout(delayQue,1000)
        assignVals(row)
    }
    else if(row < vals.length){
        setTimeout(delayQue,50)
        assignVals(row)
    }else{
        StepData(stepCol,stepVal,count)
    }
    row++
    count++

}

From what I can gather, and correct me if I'm wrong, you're wanting to make a web request and wait depending on the status?

You're adding things like setTimeout delays in your question but providing no code of what you're doing thus far so it's hard to understand what exactly you're asking here.

If you're asking about delaying a new request because of a 202 response, you could just return new Promise(resolve => setTimeout(resolve, 2500)); instead and make the web request in the next promise or something. This is all situation dependent.

I'm just gonna write a simple promise chain from memory (it may have to be tweaked to be functional) using fetch .

fetch('myapi.com/resource')
  .then((response) => {
    if (response.status == 200)
      return Promise.resolve() // Immediately resolve a new promise and send it on.
    else if (response.status == 202)
      new Promise(resolve => setTimeout(resolve, 2500)) // Wait 2.5 seconds then resolve.
  })
  .then(() => {
    // continue on with the next request.
  })
  .catch((err) => console.log(err));

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