【发布时间】:2016-07-26 06:06:21
【问题描述】:
我在 Node 中使用 bluebird,但我对使用 Promises 还是很陌生,尤其是当事情开始超出基础时。
这是我需要使用 Promises 构建的函数,我正在努力找出设置它的最佳方法。在高层次上,此函数将获取模型对象并返回它,将任何查询属性转换为其结果集。例如,一个属性的值可以是“query(top5Products)”,我们需要查找该命名查询并将该值替换为该查询的结果。属性也可以是一个实际的基于字符串的查询(使用 RQL,例如“eq(contentType,products)&&limit(5,0)”)这个转换后的模型对象将用于绑定模板。
这是我的伪代码函数,目前是同步的,除了对现有的返回承诺服务的调用...
function resolveQueryPropertiesOnModel(model) {
for (let property in model) {
if (model.hasOwnProperty(property)) {
let queryName = this.getNameOfNamedQuery(model[property]); // will return undefined if the property is not a named query
if (queryName) {
// this property is a named query, so get it from the database
this.getByName(queryName)
.then((queryObject) => {
// if queryObject has a results propery, that's the cached resultset - use it
if (queryObject && queryObject.results) {
model[property] = queryObject.results;
}
else {
// need to resolve the query to get the results
this.resolve(queryObject.query)
.then((queryResults) => {
model[property] = queryResults;
});
}
};
}
else if (this.isQuery(model[property]) { // check to see if this property is an actual query
// resolve the query to get the results
this.resolve(model[property])
.then((queryResults) => {
model[property] = queryResults;
});
}
}
}
// return some sort of promise that will eventually become the converted model,
// with all query properties converted to their resultsets
return ???;
}
在使用逻辑循环和一些预先存在的承诺并将它们混合在一起时,我仍然非常生疏。
任何帮助将不胜感激。
【问题讨论】:
标签: javascript node.js promise bluebird