Q is the promise resolved before completion?
I think that maybe I am missing something fundamental about how a promise works because I never get the expected result, so I hope someone can correct my thoughts.
In this case, it is a relatively simple challenge. I have an angular factory that, among other things, gets some data from an API (which makes a mongodb call). Since there is a $ http request (which is asynchronous), I wrapped the http call in a $ q function that should return resolve
on success and reject
if an error.
factory.loadLayout = function (layoutName) {
return $q(function(resolve, reject){
$http.get('/api/getlayout/'+layoutName)
.success(function (data) {
layout = data;
console.log("Got " + layout.name);
resolve('OK');
})
.error(function(data,status,headers,config){
reject(new Error( status));
});
});
}
Then I have another function that depends on the data collected in the first function called getButtonId, but as far as I can tell, and even if wrapped in .then
, it seems like it gets called before the promise is resolved.
var promise = padArea.loadLayout(layoutName);
promise.then(padArea.getButtonId('A0'));
So what am I missing?
== UPDATE == So try the same thing using q.defer
factory.loadLayout = function (layoutName) {
var defer = $q.defer()
$http.get('/api/getlayout/'+layoutName)
.success(function (data) {
layout = data;
console.log("Got " + layout.name);
defer.resolve('OK');
})
.error(function(data,status,headers,config){
defer.reject(new Error( status));
});
return defer.promise;
}
Still not working as I expect and the function is inside. then is still called before the HTTP completes.
== UPDATE 2 == OK so it works (if I just call the function in the factory inside. Then it calls it directly, however if I wrap it in a function like below it all unexpectedly works. Why though as it seems to me that wrapping a function call inside a function shouldn't make any difference, just by calling the function.
padArea.loadLayout(layoutName).then(function(result){
padArea.getButtonId('A0')
});
, , (, ), .
to share
$http
:
factory.loadLayout = function (layoutName) {
return $http.get('/api/getlayout/'+layoutName)
.success(function (data) {
layout = data;
console.log("Got " + layout.name);
resolve('OK');
})
.error(function(data,status,headers,config){
reject(new Error( status));
});
}
...
factory.loadLayout(param).then(function (response) { ... });
$q
factory.loadLayout = function (layoutName) {
var defer = $q.defer();
$http.get('/api/getlayout/'+layoutName)
.success(function (data) {
layout = data;
console.log("Got " + layout.name);
defer.resolve('OK');
})
.error(function(data,status,headers,config){
defer.reject(new Error( status));
});
return defer.promise;
}
to share
$q.defer():
deferred = $q.defer();
$http.get('/api/getlayout/'+layoutName)
.success(function (data) {
layout = data;
deferred.resolve("OK");
})
.error(function (data,status,headers,config){
deferred.reject(new Error(status));
})
return deferred.promise;
, HTTP- .
to share