Reputation: 6381
In my Angular application I am trying call a series of functions, each one returning a value which becomes the input for the next one. Conceptually it is something like this:
$scope.createPanel = function() {
var primer3_parameter_id = primer3FromDesignSetting($scope.selector.designSetting);
var panel = getPanelData(primer3_parameter_id);
Restangular.all('batches').post(panel).then(function(batch) {
createBatchDetailRows(batch);
});
};
I have discovered this will not work, due to async nature of the remote calls: they return a promise rather than an actual result.
I assume I need to do something like this:
$scope.createPanel = function() {
primer3FromDesignSetting($scope.selector.designSetting)
.then(getPanelData(primer3_parameter_id))
.then(postPanel(panel)) // the Restangular call wrapped into a new function
.then(createBatchDetailRows(batch))
.catch(function(err) {
// error handler
}
};
function primer3FromDesignSetting(designSetting) {
var primer3Parameter = _.clone(Restangular.stripRestangular(designSetting));
primer3Parameter = _.omit(primer3Parameter,panelFields);
delete primer3Parameter.id;
Restangular.all('primer3_parameters').post(primer3Parameter).then(function(newPrimer3Parameter)
{
return newPrimer3Parameter.id;
}, function(error) {
console.log(error);
});
}
$scope.createPanel();
But I can't quite get my head around the correct syntax.
Upvotes: 1
Views: 643
Reputation: 413
Each promise will return a successHandler and error handler. So the structure would be something like this:
primer3FromDesignSetting($scope.selector.designSetting)//Asynchronous task that returns a promise
.then(SuccessHandler1,ErrorHandler1) //Promise 1 - ErrorHandler optional
.then(SuccessHandler2,ErrorHandler2) //Promise 2 - ErrorHandler optional
.then(SuccessHandler3, ErrorHandler3) //Promise 3 - ErrorHandler optional
Here's how the promises would work(According to google employees Shyam Sheshadri (formerly of google) and Brad Green (Angular Team)):
Each asynchronous task will return a promise object.
Each promise object will have a then function that can take two arguments, a success handler and an error handler.
The success or the error handler in the then function will be called only once, after the asynchronous task finishes.
Upvotes: 1
Reputation: 52847
If you want to chain an async call, then return a promise (notice the return value). The resolution of that promise will be passed as an argument to the next then handler (in this case, it is newPrimer3Parameter.id):
function primer3FromDesignSetting(designSetting) {
var primer3Parameter = _.clone(Restangular.stripRestangular(designSetting));
primer3Parameter = _.omit(primer3Parameter,panelFields);
delete primer3Parameter.id;
return Restangular.all('primer3_parameters').post(primer3Parameter).then(function(newPrimer3Parameter)
{
return newPrimer3Parameter.id;
}, function(error) {
console.log(error);
});
}
Upvotes: 1