Reputation: 1
I have to timeout the function uploadData
whenever the rest call fails due to some condition. I have tried with setInterval
in a catch
block but it didn't give me the required results. So how can I code to timeout my function in a failure condition within 5000ms? This is my code:
uploadData(filename,callback){
formData={
'filename'=fs.createReadStream(filename)
}
options{
methiod:POST,
url:url,
auth:this.auth,
headrers:this.headers,
formData:formData
}
rp(options).then((repos)=>{
var response={
'file':filename,
'status':'success',
'message':repos,
};
return callback(response);
}).catch(fn=setInterval((err)=>{
var response={
'file':filename,
'status':'failes',
'message':err.message,
}
return callback(response);
},5000));
}
Upvotes: 0
Views: 56
Reputation: 8515
A good way to accomplish such a feature is to use Promise.race
with two promises: first is the one which makes a request, and the second is a timeout promise which resolves after a fixed time. Example:
const timeout = new Promise((resolve) => {
setTimeout(() => resolve({ timeout: true }), 5000);
});
const formData = {
'filename'=fs.createReadStream(filename)
}
const options = {
method: 'POST',
url,
auth: this.auth,
headrers: this.headers,
formData: formData
}
const request = rp(options);
// The first one to resolve will be passed to the `.then()` callback
Promise.race([request, timeout]).then((response) => {
if (response.timeout === true) {
return console.log('timeout');
}
console.log('api response', response);
});
Upvotes: 2