如何中断Promise链

如何中断Promise链

  • 创建一个Promise实例
const promise = new Promise(function(resolve, reject) {
  // ... some code

  if (/* 异步操作成功 */){
    resolve(value);
  } else {
    reject(error);
  }
});
  • 使用then方法
promise
.then(res=>{
	// success
})
.catch(err=>{
	// failure
})

  • 如果要在Promise链中中断.then方法
    • 方法1 throw err
      promise
      .then(res=>{
      	if(!res){
      		throw err // 抛出错误
      	}
      })
      
    • 方法2 reject
    promise
    	.then(res=>{
    		if(!res){
    			reject // 使用reject方法
    		}
    	})
    
  • Promise相关的第三方库
    promise-fun
    这种then()中中断promise链的实现可以使用里面的
    p-if: Conditional promise chains

你可能感兴趣的:(前端,JavaScript)