I'm trying to understand promises and $q in AngularJS. I'd like to chain 2 functions, and execute them in order. The first is a file upload, and can take a while, so I need to wait for it to be executed before creating a DB record for it. I was originally using angular 1.3, hence the .success and .error methods.
Here's the code:
//image upload function
$scope.imageUpload = function(){
return $q(function (resolve, reject) {
var fd = new FormData();
fd.append("file", $scope.imageFile);
var data = fd;
var url = 'http://myApiUrl';
var postObject = {
method: 'POST',
url: url,
data: data
}
$http(postObject)
.success(function(response) {
return response;
}).error(function(response) {
return response;
});
})
}
// create a DB record
$scope.recordCreate = function(previousResponse){
return $q(function (resolve, reject) {
// does stuff with previousResponse, and creates a db record
})
};
// do functions in order
$scope.imageUpload().then(
$scope.recordCreate(response)
);
Not only am I getting the error
ReferenceError: response is not defined
(in relation to that last line, $scope.recordCreate(response)), but also the second function is executing BEFORE the first!
I have tried to follow the docs here https://docs.angularjs.org/api/ng/service/$q but in my example I can't get my first function to return a response to the 2nd. Does anyone know why?