我怎么能中止JavaScript承诺?

时间:2016-09-21 19:10:23

标签: javascript node.js promise chaining

我在NodeJS项目上工作,我在我的代码中使用了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);
})

2 个答案:

答案 0 :(得分: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,如原始代码所暗示的那样。

答案 1 :(得分: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);
}
//****

})