2016-09-21 45 views
1

我的工作NodeJS项目,我用承诺在我的代码 到链的一些方法,我需要在“thens”链我怎么能放弃JavaScript Promise?

findEmployeeByCW('11111', "18-09-2016"). 
then(function() { 
    return findEmployeeByCWE('111111', "18-09-2016", '111111') 
}, function() { 
    console.log('createEmployeeLoginBy') 
    createEmployeeLoginBy('111111', "18-09-2016", '111111'). 
    then(function (log) { 
     SaveEmployeeLogToDb(log) 
     // *************** 
     // ^_^ I need to exit here .... 
    }) 
}) 
.then(function (log) { 
    return updateLoginTimeTo(log, '08-8668', '230993334') 
}, function() { 
    return createNewEmployeeLog('224314', "18-09-2016", 
     '230993334', '08-99') 
}) 
.then(SaveEmployeeLogToDb).then(DisplayLog).catch(function (e) { 
    console.log(e); 
}) 
+0

您可以存储对您的承诺的引用,然后在'SaveEmployeeLogToDB'后面调用'reject'' –

+0

您可以抛出一个错误并且承诺将被拒绝 –

+0

@mortezaT不幸的是我使用了它,但是它执行了下一个拒绝 –

回答

0

您当前无法“取消”的承诺之一中止。但你可以使用一个例外:

findEmployeeByCW('11111', "18-09-2016"). 
then(function() { 
return findEmployeeByCWE('111111', "18-09-2016", '111111') 
}, function() { 
console.log('createEmployeeLoginBy') 

//*** "return" added 
return createEmployeeLoginBy('111111', "18-09-2016", '111111'). 
then(function (log) { 
SaveEmployeeLogToDb(log) 

//**** 
throw new Error('promise_exit'); 
//**** 

}) 
}) 
.then(function (log) { 
return updateLoginTimeTo(log, '08-8668', '230993334') 
}, function() { 
return createNewEmployeeLog('224314', "18-09-2016", 
'230993334', '08-99') 
}) 
.then(SaveEmployeeLogToDb).then(DisplayLog).catch(function (e) { 

//**** 
//Only log if it's not an intended exit 
if(e.message != 'promise_exit'){ 
    console.log(e); 
} 
//**** 

}) 
+0

我以前试过了,它没有工作,它继续执行,我也尝试在SaveEmployeeLogToDb方法中抛出一个异常,但它也失败了! –

+0

尝试更新的答案。返回createEmployeeLoginBy应该可以工作。 –

2

如果我理解正确的意图,这里没有必要取消或抛出。

您应该能够通过重排来实现你的目的:

findEmployeeByCW('11111', "18-09-2016") 
.then(function() { 
    return findEmployeeByCWE('111111', "18-09-2016", '111111') 
    .then(function(log) { 
     return updateLoginTimeTo(log, '08-8668', '230993334'); 
    }, function(e) { 
     return createNewEmployeeLog('224314', "18-09-2016", '230993334', '08-99'); 
    }); 
}, function(e) { 
    return createEmployeeLoginBy('111111', "18-09-2016", '111111'); 
}) 
.then(SaveEmployeeLogToDb) 
.then(DisplayLog) 
.catch(function(e) { 
    console.log(e); 
}); 

这应该与一个log对象总是通过该点的所有可能的路径传递到SaveEmployeeLogToDb条件的工作,由最初的暗示码。

+0

Mr @ Roamer-1888你的意思是我应该建立我的系统,以便我不需要取消!! ??也许这是一个解决方案,但如果我需要通过编码来中止,我应该重建单个代码的系统? –

+0

非常感谢您的建议Mr @ Roamer-1888,它对我很有用,我认为Promise的主要构想是很好地构建系统,如果发生错误,它应该冒泡以便在链接 –