如何中断promise.all(以多文件上传为例)

方案一

const CancelToken = axios.CancelToken;

// 发送文件
getFn(file) {
  		const formdata=new FormData();
        formdata.append('file',file);
      
        return this.$axios({
          method: "post",
          url: "/upload",
          data: formdata,
          cancelToken: new CancelToken(c => {  //强行中断请求要用到的
    			this.cancel.push(c)
		  }),
          headers: {
            "Content-Type": "application/x-www-form-urlencoded;"
          }
        }).then(res=> {
          console.log(res, 78);
        });
}
// 利用promisep批量发送文件
sendFile() {
 const lists = [getFn(file1), getFn(file2), getFn(file3)]
 promise.all(lists)
}
// 点击终止停止发送所有文件 
closeFile() {
    this.cancel.forEach(fn=> {
      fn('中断请求')
    })   
},

方案二

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

// 发送文件
getFn(file) {
  		const formdata=new FormData();
        formdata.append('file',file);
      
        return this.$axios({
          method: "post",
          url: "/upload",
          data: formdata,
          cancelToken: source.token,
          headers: {
            "Content-Type": "application/x-www-form-urlencoded;"
          }
        }).then(res=> {
          console.log(res, 78);
        }).catch(function (thrown) {
			  if (axios.isCancel(thrown)) {
			    console.log('Request canceled', thrown.message);
			  } else {
			    // handle error
			  }
		});
}
// 利用promisep批量发送文件
sendFile() {
 const lists = [getFn(file1), getFn(file2), getFn(file3)]
 promise.all(lists)
}
// 点击终止停止发送所有文件 
closeFile() {
    source.cancel('Operation canceled by the user.'); 
},

Axios官方github示例:

https://github.com/axios/axios#cancellation


版权声明:本文为hzxOnlineOk原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。