ES6/When.js - 处理递归承诺链中的承诺解析
ES6/When.js - Handling promise resolution in recursive promise chain
我有一个递归的承诺链,即调用自身直到值等于零。这很好用,但是当它最终解决时,输出会附加 "undefined" 值,大概是每个未解决的 promise 调用一个。
问题:任何人都可以就处理预期未解决值的最佳实践提出建议吗?
我能想到的选项:
1) 在结果集中处理这些,即删除未定义的值,例如
_.compact(response)
感觉这不是正确的选择,但可能是?
2) 抛出异常由catch处理
感谢任何想法 - 有助于说明以下问题的代码框架。
const queueTask = function queueTask(task) {
...
}).then(response => {
if (_.has(task, 'another')) {
let taskConfigs = doSomething(task);
//Add new tasks to queue. Return a promise that will resolve
//only once all the items in array have resolved.
return when.all(taskConfigs.map(function(each) {
return queueTask(each);
}));
}
if (task.remainingTasks === 0) {
return response;
}
}).catch(function (err) {
....
};
感谢@SergiuParaschiv 的评论,这是预期的行为。
我通过简单地使用下划线 _.compact
方法删除 "undefined" 响应来解决这个问题。
首先,我发现您的代码存在两个问题:
当条件 _.has(task, 'another')
和 task.remainingTasks === 0
都为假时,您想要什么样的响应,猜测这是您的 undefined
值的来源。
你直接返回when.all
response,是一个数组,是你想要的吗?
我会将您的代码修改为:
}).then(response => {
if (_.has(task, 'another')) {
let taskConfigs = doSomething(task);
return when.all(taskConfigs.map(function(each) {
return queueTask(each);
})).then(resultArray => response); // or whatever kind of result you want to post.
}
return response;
}).catch(function (err) {
我有一个递归的承诺链,即调用自身直到值等于零。这很好用,但是当它最终解决时,输出会附加 "undefined" 值,大概是每个未解决的 promise 调用一个。
问题:任何人都可以就处理预期未解决值的最佳实践提出建议吗?
我能想到的选项:
1) 在结果集中处理这些,即删除未定义的值,例如
_.compact(response)
感觉这不是正确的选择,但可能是?
2) 抛出异常由catch处理
感谢任何想法 - 有助于说明以下问题的代码框架。
const queueTask = function queueTask(task) {
...
}).then(response => {
if (_.has(task, 'another')) {
let taskConfigs = doSomething(task);
//Add new tasks to queue. Return a promise that will resolve
//only once all the items in array have resolved.
return when.all(taskConfigs.map(function(each) {
return queueTask(each);
}));
}
if (task.remainingTasks === 0) {
return response;
}
}).catch(function (err) {
....
};
感谢@SergiuParaschiv 的评论,这是预期的行为。
我通过简单地使用下划线 _.compact
方法删除 "undefined" 响应来解决这个问题。
首先,我发现您的代码存在两个问题:
当条件
_.has(task, 'another')
和task.remainingTasks === 0
都为假时,您想要什么样的响应,猜测这是您的undefined
值的来源。你直接返回
when.all
response,是一个数组,是你想要的吗?
我会将您的代码修改为:
}).then(response => {
if (_.has(task, 'another')) {
let taskConfigs = doSomething(task);
return when.all(taskConfigs.map(function(each) {
return queueTask(each);
})).then(resultArray => response); // or whatever kind of result you want to post.
}
return response;
}).catch(function (err) {