问题
I know there are several threads on this, but I think in SAPUI5 context no thread answers this general topic on deferred/sync calls in SAPUI5.
In My Controller I got :
test : function() {
var dfd = $.Deferred();
var sServiceUrl = '/sap/opu/odata/sap/xyz/MySet?$format=json';
var post = $.ajax({
url: sServiceUrl,
type: "GET"
});
post.done(function(data){
console.log(data);
dfd.resolve();
});
post.fail(function(){
console.log("Error loading: " + sServiceUrl);
dfd.reject();
});
return dfd.promise();
},
in My view I am calling the method AND I want to wait for the result, how to I manage it correctly?
var test = oController.test();
console.log(test);
$.when(test).done().then(console.log("finished"));
also this approach does not wait:
$.when(oController.test()).then(console.log("finished"));
As expected, test is undefined, "finished" is logged, and when .done from method is ready, it is logged. but I want to wait for it (and in best case return data from ajax back)..
how do I wait for post.done() to continue in my view?
回答1:
()
operator invokes the function. You are invoking the function yourself, the function is not called by the then
method. What happens is you call the log
function and it's returned value is set as the handler. Since you want to pass an argument to the console.log
method, you can use an anonymous function:
dfd.resolve(data);
// ...
$.when(oController.test()).then(function(data) {
console.log('finished', data);
});
来源:https://stackoverflow.com/questions/26710877/sapui5-wait-for-an-deferred-object-wait-for-done-function