以下代码片段是一个nodeJS控制器方法,调用返回延迟承诺的服务。我试图了解处理多个存在点的最佳方法。
例如,如果服务返回一个空对象,我希望承诺链存在,并将响应"此处未找到任何内容"返回给用户。如果它确实找到了什么,它就会从步骤 1 移动到承诺链中的下一项,即第 2 步。
从我的测试来看,它似乎返回了 json 响应,然后进入下一个逻辑步骤,即步骤 2。此逻辑现在无法在服务中处理,即如果没有找到返回错误的项目。
module.exports.show = function (req, res) {
service.getItem(itemId)
.then(function (item) {
if (!item) {
return res.json('Nothing found here');
}
// Step 1
// do some work on the item
return item;
})
.then(function (foundItem) {
// Step 2
// do some more work on the item
return res.json('Item has changed ' + foundItem);
})
.catch(function (err) {
return res.json(err);
});
};
尝试以下代码。捕获处理程序捕获了错误。我还更改了 if 子句(我假设这就是您的实际意思(:
module.exports.show = function (req, res) {
service.getItem(itemId)
.then(function (item) {
if (!item) {
throw new Error('Nothing found here');
}
// Step 1
// do some work on the item
return item;
})
.then(function (foundItem) {
// Step 2
// do some more work on the item
return res.json('Item has changed ' + foundItem);
})
.catch(function (err) {
return res.json(err);
});
};
请记住,then
总是返回一个承诺。如果您自己不返回承诺,则会自动使用返回值创建已解决的承诺。
所以,return res.json('Nothing found here')
和return Promise.resolve(res.json('Nothing found here'));
一样,这意味着下一个then
将被召唤。
如果你不想执行下一个,你只需要拒绝承诺:
throw new Error('Nothing found here'));
// ...
.catch(function (err) {
return res.json(err.message);
});
顺便说一句,您可能是指if (!item)
,而不是if (item)
:
if (!item) {
throw new Error('Nothing found here');
}
如果步骤 1 和 2 是同步的,则:
module.exports.show = function (req, res) {
service.getItem(itemId).then(function (item) {
if (!item) {
throw new Error('Nothing found here'); // this will be caught below
}
item = doWork_2(doWork_1(item)); // Steps 1 and 2:
return res.json('Item has changed ' + item);
}).catch(function (err) {
return res.json(err.message);
});
};
其中doWork_1()
和doWork_2()
都返回已处理item
。
如果步骤 1 和 2 是异步的,则
:module.exports.show = function (req, res) {
service.getItem(itemId).then(function (item) {
if (!item) {
throw new Error('Nothing found here'); // this will be caught below
} else {
return doWork_1(item).then(doWork_2); // Step 1, then Step 2
}
})
.then(function (item) {
return res.json('Item has changed ' + item);
}).catch(function (err) {
return res.json(err.message);
});
};
其中doWork_1()
和doWork_2()
返回使用已处理item
解决的承诺。
如果不确定doWork_1()
和.doWork_2()
是同步的还是异步的,则使用以下模式,它将处理这两种可能性:
module.exports.show = function (req, res) {
service.getItem(itemId).then(function (item) {
if (!item) {
throw new Error('Nothing found here'); // this will be caught below
} else {
return item;
}
})
.then(doWork_1) // Step 1
.then(doWork_2) // Step 2
.then(function (item) {
return res.json('Item has changed ' + item);
}).catch(function (err) {
return res.json(err.message);
});
};