Bluebird的递归承诺没有返回
Recursive Promise in Bluebird not returning
我读过了生成一个依赖于递归承诺的承诺用bluebird链接递归承诺递归的承诺吗?但我仍然不知道我的承诺有什么问题
我从数据库中获取对象。每个对象都有一个字段,但有时它有一个对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"
}
}
因此,我使用承诺和递归来尝试这一点,但我不知道我的承诺出了什么问题。我得到了这个结果
{
"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;})
}
问题是a)你的映射函数没有return
,所以它不是等待b)你不应该在这里使用map
。
完美的解决方案是Bluebird的Promise.props
,它等待对象属性上的承诺。
function getUuid(value) {
if (typeof value != "string") return null;
var uuid = value.match(/'w{8}(-'w{4}){3}-'w{12}?/);
if (uuid) return uuid[0];
return null;
}
function getExpandedObj(uuid, recursiveLevel) {
return getObj(uuid).then(function(obj) {
// prevent infinite recursion
if (recursiveLevel <= 0)
return obj;
for (var property in obj) {
var uuid = getUuid(obj[property])
if (uuid) {
obj[property] = getExpandedObj(uuid, recursiveLevel-1);
}
}
return Promise.props(obj);
});
}
尝试更改
obj[property] = getExpandedObj(uuid, recursiveLevel-1)
.then(function(exObj) {
return exObj;
});
return getExpandedObj(uuid, recursiveLevel-1)
.then(function(exObj) {
obj[property] = exObj;
return obj;
});
,因为您将值设置为承诺对象而不是实际值。
相关文章:
- 谷歌日历 api 调用可以在角度工厂内返回承诺吗?
- JavaScript - 返回承诺和/或调用回调
- 在同一函数中解析承诺后返回承诺
- 承诺返回承诺
- 承诺返回承诺
- 如何从多个承诺中返回承诺
- 如何使用在 AngularJS 中返回承诺的$resource测试工厂
- 这是一种常见的模式吗?(返回数据而不是返回承诺)
- 使用 Jasmine 2.4.* 测试返回承诺的服务
- 承诺回调返回承诺
- 可以 Angular 模板调用函数返回承诺
- 链接返回承诺数组的函数
- 使用属性从指令返回承诺
- 节点.js SQLite 3 返回承诺
- 从延迟的回调中返回承诺
- 返回承诺与返回承诺内未定义之间的区别
- 返回承诺值
- 如何在返回承诺的服务中创建 reset() 方法
- 从顺序 jQuery ajax 调用返回承诺
- 在 Redux Thunk 发货后从商店返回承诺