【发布时间】:2014-03-01 20:40:04
【问题描述】:
在我的代码中,根据特定条件,我想跳到done 函数,而不考虑所有then 函数。
这个问题的原始版本在编辑中。以下是我正在处理的实际问题。很抱歉给您带来不便
实际问题:
我正在读取一个文件并处理它。如果文件的内容符合某些条件,我必须对文件系统进行一系列操作(比如读写几个文件),然后执行done函数。如果条件不成立,我要跳过所有的一系列操作,直接执行done函数。
我在所有then 函数中返回一个对象(比如说result),在接下来的then 中我更新result 并返回它。因此,当所有then 完成后,done 将具有累积的result。最后done会处理result并打印出来。
因此,如果最初不满足条件,done 将简单地打印result(将为空)。
Q()
.then(readFile)
.then(function (contents) {
var processResult = process the contents;
if (processResult) {
return {};
} else {
// How can I skip to `done` from here
}
})
.then(function (results) {
// do some more processing and update results
return results;
})
... // Few more then functions similar to the one above
...
.fail(function (exception) {
console.error(exception.stack);
})
.done(function (results) {
// do some more processing and update results
console.log(results);
});
【问题讨论】:
-
虽然不确定,但你不能返回一个包含布尔值的对象吗,根据这个布尔值,你的下一个函数将执行是/否。
return { randomNumber : ..., process : true };,在您的下一个电话中:.then(function (data) { if(!data.process) return; return data.randomNumber + 1; }) -
@DieterGoetelen 这将使下一个处理功能非常依赖于上一步。
-
你能用一个更真实的问题吗(也许你的实际任务,有很多伪代码会发生什么)?您的同步示例并没有多大意义。
标签: javascript node.js promise q