【发布时间】:2015-08-25 17:41:41
【问题描述】:
我读过 Produce a promise which depends on recursive promises chaining recursive promise with bluebird Recursive Promises? 但我仍然无法弄清楚我如何构建我的承诺有什么问题
所以我从数据库中获取对象。每个对象都有一个字段,但有时它有一个对 UUID 的引用。所以举个例子,如果一个人有一个朋友和一个妈妈,那就是
{
"id": e872530a-27fc-4263-ad39-9a21568c31ef,
"name": "dood",
"friendId": "571746fc-686d-4170-a53e-7b7daca62fa0",
"motherId": "99b65849-1f1c-4881-a1d0-c5ae432e83a2"
}
现在,我的想法是当我获取一个对象时,我想用扩展版本替换任何其他 UUID。
{
"id": e872530a-27fc-4263-ad39-9a21568c31ef,
"name": "dood",
"friendId": {
"id": "571746fc-686d-4170-a53e-7b7daca62fa0",
"name": "peter"
},
"motherId": {
"id": "99b65849-1f1c-4881-a1d0-c5ae432e83a2",
"name": "ma"
}
}
因此,我使用 Promise 和递归来尝试这个,但我无法弄清楚我的 Promise 出了什么问题。我得到了这个结果
{
"id": e872530a-27fc-4263-ad39-9a21568c31ef,
"name": "dood",
"friendId": {
"isFulfilled": False,
"isRejected": False
},
"motherId": {
"isFulfilled": False,
"isRejected": False
}
}
我用的是 bluebird js,下面是代码的样子
function getExpandedObj(uuid, recursiveLevel) {
return getObj(uuid) //This gets the object from the database
.then(function(obj) {
//I convert the obj to an array where each element is
//{property:value} so I can do a map over it
// some code to do that, I think it's irrelevant so I'll
// skip it
return objArr;
})
.map(function(obj) {
//prevent infinite recursion
if (recursiveLevel > 0) {
for (var property in obj) {
if (typeof(obj[property]) === "string" ) {
var uuid = obj[property].match(/(\w{8}(-\w{4}){3}-\w{12}?)/g);
if (uuid != null) {
uuid = uuid[0];
obj[property] = getExpandedObj(uuid, recursiveLevel-1)
.then(function(exObj) { return exObj;})
}
}
}
}
})
.then(function(obj) {return obj;})
}
【问题讨论】:
标签: javascript promise bluebird