Let's consider a situation where I have implemented a search function to make an HTTP call. Each call made can have varying durations, and it is crucial for the system to cancel any previous HTTP requests and only await results from the latest call.
async function search(timeout){
const data = await simulateHTTPRequest(timeout)
return data;
}
// The simulateHTTPRequest function is used purely for representational purposes
function simulatedHTTPRequest(timeout){
return new Promise(resolve,reject){
setTimeout(function(){
resolve()
},timeout)
}
}
search(200)
.then(function(){console.log('search1 resolved')})
.catch(function() {console.log('search1 rejected')})
search(2000)
.then(function(){console.log('search2 resolved')})
.catch(function(){console.log('search2 rejected')})
search(1000)
.then(function(){console.log('search3 resolved')})
.catch(function(){console.log('search3 rejected')})
The desired output needs to display "search1 resolved", "search2 rejected", and "search3 resolved".
How can this particular scenario be achieved?