谁能告诉我我在这里做错了什么?
我有一个 promise ,当返回结果时,它会失去局部变量范围。
我需要延迟调用完成时可用的 id 值:
getChildren:function(id){
service.getChildren(id)
.then(function(result){
var parentId = id //null
return result
})
.fail(function (error) {
log.error(error);
})
}
最佳答案
您是否期望从调用 getChildren()
返回结果
?
如果是这样(假设 service.getChildren()
返回一个 jQuery Promise),代码需要稍微修改一下,以便 .getChildren()
返回一个 promise 稍后交付结果
:
这可以通过以下方式实现:
getChildren:function(id) {
return service.getChildren(id).done(function(result) {
//here do something generic with `result`
}).fail(function (error) {
log.error(error);
});
}
并且 .getChildren()
可能会按如下方式调用:
myObj.getChildren(myID).done(function(result) {
//here do something specific with `result`
});
注意:这里似乎不需要 .then()
的额外功能,但如果您想 promise 交付 result
之外的其他内容,则需要额外的功能。
关于Javascript Promise/然后失去范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15953080/