首页 文章

如何打破嵌入另一个承诺链的承诺链

提问于
浏览
0

我无法弄清楚如何将嵌套的promise链断开成主要的promise链 . 这是我的代码:

//Main Promise chain
 let promiseMain = Promise.resolve(1)
        .then(result => functionA())
        .then(result => nestedChain()).catch((error) => {
            console.log(error);
        })
        .then(result => functionC())

//chain error handler
function chainError(err) {
return Promise.reject(err)
};

function nestedChain()
{
stepOne()
.then(stepTwo, chainError)
.then(stepThreee, chainError)
.catch((error) => 
    {
        console.log(error);
        return undefined;
    });          
}

function stepOne() 
{
    return chainError("error attempt : 1.00");
}

一旦我进入nestedChain,我在stepOne()中抛出一个错误,我就能打破这个nestedChain . 真棒!

问题:它也打破了主要的承诺链 . 因此..当它进入nestedChain()并且从stepOne()抛出错误时,主promise链中的functionC将永远不会执行,因为来自nestedChain的被拒绝的promise也会破坏此链 .

3 回答

  • 0

    如果我理解你是正确的,你需要在嵌套链承诺后捕获错误

    Promise.resolve().then(()=> {
      console.log('A');
    }).then(() => {
      return Promise.resolve().then(() => {
        console.log('step 1');
      }).then(() => {
        console.log('step 2');
        throw new Error('Step 2 error');
      });
    }).catch((err) => {
      console.log(err);
    }).then(() => {
      console.log('C');
    });
    
  • 1

    承诺是为了等待需要更多时间的事情 . 您只需要正确实现承诺 .

    例如,如果我们有3个函数返回promise和一个嵌套函数也返回promise,这就是它的实现方式:

    functionA()
    .then( result => {
        return functionB();
    })
    .then( result => {
        return nestedFunct();
    })
    .then( result => {
        return functionC();
    })
    .then( result => {
        console.log(result);
    })
    .catch( error => {
        console.log(`Error in one of the above function`);
    });
    

    所有功能的格式也相似

    function functionA() {
        return new Promise( (resilve, reject) => {
            resolve('something');
            // or
            reject('Error');
        });
    }
    

    嵌套函数可以是这样的

    function nestedFunc() {
        return functionD()          // Return promise
        .then( result => {
            return functionE();     // return promise
        })
        .then( result => {
            return functionF();      // return promise or value
        });
    }
    

    主要承诺链不受个别功能的影响,只要它们保持回报承诺 . 所有个人职能都可以拥有本地承诺链 . 即使嵌套链中发生错误也会被主承诺链中的 catch() 捕获 .

  • 0

    你必须附上承诺链,做这样的事情

    function nestedChain()
    { 
      stepOne()
      .then(stepTwo, chainError)
      .then(stepThreee, chainError)
      .catch ((error) => {
                   console.log(error);
                   return undefined;
                })
    }
    

相关问题