当节点js中的rest调用失败时,如何超时功能?

每当由于某种情况而使其余调用失败时,我必须使函数uploadData超时。我在setInterval块中尝试过catch,但没有得到所需的结果。那么,如何在5000ms的故障条件下使我的函数超时?这是我的代码:

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));
}
wxp1818118 回答:当节点js中的rest调用失败时,如何超时功能?

实现此功能的一个好方法是使用带有两个承诺的Promise.race:第一个是发出请求的承诺,第二个是超时承诺,它在固定时间。示例:

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);
});
本文链接:https://www.f2er.com/3168217.html

大家都在问