从Deferred.Done中检索返回值 [英] Retrieving a Return value from a Deferred.Done
问题描述
基本上我有各种javascript控制器。基本HTML文档调用一个javascript对象,该对象调用另一个调用Ajax调用并返回Deferred对象的javascript对象。然后我在该数据返回时调用.done并处理它。当我处理它时,我检查数据是否包含错误。我希望能够一直返回一个真或假的链回到基本HTML文档以执行一些UI行为,但我对Deferred / promise的想法很新。正如您从最后一级的代码示例中看到的那样。我只是返回def.done(AfterServerSuccess)并返回基地以填充containsError。这似乎返回一个空的Deferred对象。我觉得有一个简单的答案。我已经尝试了不同的方法来获取完成方法的布尔值,但我无法弄明白。有人可以在这里给我一些指导吗?
Basically I have various javascript controllers. The base HTML document Calls a javascript object, which calls another one, that calls a Ajax call and returns the Deferred object. Then I call .done on that data return and process it. When I process it I check if the data contains a error. I want to be able to return a true or false all the way back up the chain to the base HTML document to perform some UI behavior but I'm quite new to the idea of Deferred/promise. As you can see from the code sample at the last level. I just do return def.done(AfterServerSuccess) and return all the way back to the base to populate containError. This seems to return an empty Deferred object. I feel like there is a simple answer to this. I've tried different ways to get the boolean out of the done method to be passed up but I can't figure it out. Can someone please provide me some guidance here?
基数:
var containError = `myJavascriptController.CheckItemsForErrors(dayparts, false);`
MyJavascriptController.js:
var CheckItemsForErrors = function (list, source)
{
return mySelectionController.CheckForErrors("CheckForErrors", list, source);
};
mySelectionController.js:
var CheckForErrors= function (listItems, source)
{
if (listItems.length > 1)
{
//Ajax call returns Deferred object
var def = _manager.SendDataToServer(listItems);
return def.done(AfterServerSuccess)
}
var AfterServerSuccess = function (data)
{
_.each(data, function (item)
{
if (item.Error == true)
{
return true;
}
});
return false;
};
推荐答案
我建议做一些关于promises和deferred对象的阅读。 这是一个很好的入门资源。
I would recommend doing some reading about promises and deferred objects. This is a good resource for getting started.
基本上,你需要让 CheckForErrors
函数返回一个延迟对象/ promise,它将由 AfterServerSuccess $ c $的结果解析c>功能。然后,在顶层,你可以写这样的东西来得到错误结果:
Basically, you need to make your CheckForErrors
function return a deferred object/promise, which will be resolved by the result of the AfterServerSuccess
function. Then, at the top level, you can write something like this to get the error result:
var containError = false;
myJavascriptController.CheckItemsForErrors(listItems, source)
.done(function (result) {
containError = result;
// Do other stuff here...
});
从这一小段代码向后工作,你会对promises / deferred的方式有所了解对象有效。
Work backwards from this little snippet of code and you'll get a feel for the way promises/deferred objects work.
这篇关于从Deferred.Done中检索返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!