fetch如何中断then?

fetch('xxxurl.com').then(res=>{
  if(res.status === 'ok') {
    console.log('我应该如何跳出,不执行下一个then?');
  } else {
    return 'ok,可以继续';
  }
}).then(res=>{
    console.log(res);
});

我希望根据状态来判断是否要执行接下来的then,应该怎么做?

阅读 6.8k
2 个回答
//以上省略
.then(()=>{
    //返回一个reject
    return Promise.reject("reject");
})
.then(()=>{
    console.log("这里不会执行");
    return Promise.resolve("resolve")
})
.catch(err=>{
    console.log("直接跳到了这里");
})

所以,你的代码应该这么写才对

fetch('xxxurl.com').then(res=>{
  if(res.status === 'ok') {
    //reject将跳过下一个then
    return Promise.reject();
  } else {
    //最好要用resolve包裹结果,而不是返回结果本身
    return Promise.resolve('ok,可以继续');
  }
}).then(res=>{
    console.log(res);
});

这样算不算一种方式:

    fetch('1.png')
        .then(function(){
            console.log(arguments);
            throw new Error('test');
        })
        .then(function(){
            console.log('end')
        })
        .catch(function(exc){
            console.log(exc);
        });
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题