我正在尝试找到链接条件查询的正确方法。
下面是一些伪代码来说明我的情况:
check whether the an item exists;
if no:
reply with status 404;
if yes:
check whether the user owns the item;
if no:
redirect to another page;
if yes:
retrieve the information about the item and render the page;我的第一个直觉是使用tasks来重用相同的连接,但由于可能的结果不同,我很难弄清楚如何正确处理这些承诺:
db.task(t => {
return t.items.exists(itemId)
.then(exists => {
if (!exists) { // item does not exist
// 404
}
return t.items.isOwner(itemId, userId)
.then(isOwner => {
if (!isOwner) {
// redirect to some other page
}
return t.items.getById(itemId);
})
})
})
.then(data => {
// OK, process data and render
})
.catch(console.error); // unexpected errors例如,如果我尝试重定向到404页面,承诺仍将在之后得到解决。另一种方法是拥有以下内容:
if (!exists) { // item does not exist
return Promise.reject('404');
}
...
.then(data => {
// OK, process data and render
}, reason => {
// KO, conditions were not met to resolve
})它“工作”,但同时捕获错误和未满足的条件。我更希望有一个专门的“未满足条件”处理程序。
我又想到了另一种方法:
var p = db.task(t => {
return t.items.exists(itemId)
.then(exists => {
if (!exists) { // item does not exist
// resolve p (and break promise chain) with something like
// p.resolve(() => {
// return res.redirect...
// });
}
// else we can go on with the queries
return t.items.isOwner(itemId, userId);
}
.then(isOwner => {
if (!isOwner) {
// resolve p and redirect to some other page
}
return t.items.getById(itemId);
})
.then(item => {
// everything OK, resolve with a handler to render the page
});
})
.then(action => {
action();
})
.catch(console.error); // unexpected errors但我看不到任何解决p的方法。在嵌套的promise中调用Promise.resolve(...)会在落入p的then之前解析下一个promise本身。
在关注性能的同时,在pg-promise中链接条件查询和处理不同结果的推荐方法是什么?
发布于 2019-09-20 01:07:21
作者的问题主要是使用promises,而不是pg-promise。
db.task('easy-peasy', async t => {
if (await t.items.exists(itemId)) {
// reply with status 404;
} else {
if (await t.items.isOwner(itemId, userId)) {
// redirect to some other page
} else {
return t.items.getById(itemId); // return the data
}
}
})
.then(data => {
if (data) {
// Task returned data;
// Render the data;
}
})
.catch(console.error); // unexpected errors发布于 2019-09-17 12:03:18
看看这对你是否有效。
这仍然需要项目通过每个promises,直到它到达最后一个then块或catch块。
// First Condition
const input = 'test input'
Promise.resolve({ item: input })
// Repeat this for different condition on `item.item` and change `X`
/* REPEAT START */
.then(data => {
if (data.hitCondition != null && data.hitCondition !== '') {
return data;
}
if (conditionX(data)) {
return Object.assign({}, data, {
hitCondition: 'conditionX'
});
}
return data;
})
/* REPEAT END */
...
.then(result => {
const { item, hitCondition } = result
if (hitCondition != null && hitCondition !== '') {
// at least one condition is met
// check hitCondition to see which condition is hit
} else {
// none of the conditions are met
}
})
.catch(error => {
// Some error happened somewhere
console.error(error);
});https://stackoverflow.com/questions/57967135
复制相似问题