繁体   English   中英

如果在 promise 中满足条件,则不执行第二个 then()

[英]Do not execute second then() if condition is met in promise

arkIsEnabled并且我们进入该方法之后,我必须停止下面的代码做任何事情。 有没有办法做到这一点?

return promise
    .then(response => {
        if (arkIsEnabled) {                
           dispatch(createArk(response));
        }
        ...
        return dispatch(operations.getLuft())
    })
    .then(response =>
        dispatch(prepareLuft())
    )
    .catch(error => {
        dispatch(resourceErrorHandler(error));
    })

您可以将then移动到要应用它的行内:

return promise
    .then(response => {
        if (arkIsEnabled) {                
           return dispatch(createArk(response)); <=== NOTICE THE RETURN HERE
        }
        ...
        return dispatch(operations.getLuft())
          .then(response =>
            dispatch(prepareLuft())
           )
    })
    .catch(error => {
        dispatch(resourceErrorHandler(error));
    })

您可以throwPromise.reject忽略then函数并转到catch来处理。

 let arkIsEnabled = true; let callBackHasToStop = async () => new Promise(resolve => resolve(1)) .then(r => { console.log(r); if (arkIsEnabled) { throw "error"; } //do st return ++r; }) .then(r => { console.log(r); //do st return ++r; }) .catch(e => { //check error here. If it is thrown from arkIsEnabled. Stop! console.log(e); if (e === "error") return; //do st console.log('last dispatch error'); }); // Other case let otherArkIsEnabled = false; let callBackHasNotToStop = async () => new Promise(resolve => resolve(1)) .then(r => { console.log(r); if (otherArkIsEnabled) { throw "error"; } //do st return ++r; }) .then(r => { console.log(r); //do st return ++r; }) .catch(e => { //check error here. If it is thrown from arkIsEnabled. Stop! console.log(e); if (e === "error") return; //do st console.log('last dispatch error'); }); let call = async () => { await callBackHasNotToStop(); console.log('-------'); console.log('2 will not return'); await callBackHasToStop(); }; call();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM