I am using angular1 and I have 4 functions that need to execute synchronously. Assume those functions are : f1 , f2, f3 , f4 and need to run in that order. f1, f2, f3, f4 are functions that are used independently in other cases. I have only one usecase where I need to execute them sequentially. I know I have to use promise and I tried as :
self.selectionPromise = function(){
var deferred = $q.defer();
console.log("Inside promise");
self.f1();
return deferred.promise;
};
And then use it as:
self.updateSelectedFile = function () {
self.selectionPromise()
.then(self.f2() )
.then(self.f3() )
.then(self.f4() )
}
Does not seem to resolve my issue. I am seeing error: **TypeError: Cannot read property 'then' of undefined and additionally, the functions are not in order **
May I get help on how to use expect to synchronise these 4 functions?
Here is the hint on the code structure:
Function F1:
self.setRecordCount = function ()
{
var deferred = $q.defer();
if (!self.selectedFile)
{
self.recordCount = 0;
return;
}
self.fileInfo = {fileLocation: self.folderPath + self.selectedFile};
FileService.getRecordCount(self.fileInfo)
.then(
function (count)
{
//do something
},
function (errResponse)
{
self.recordCountError = "Error while getting record count for file: " + self.folderPath + self.selectedFile;
}
)
.then(function finishUp(response)
{
console.log("returning from recordCount");
})
;
deferred.resolve("RecordCount");
deferred.promise;
}
function F2:
self.detectDelimiter = function () {
var deferred = $q.defer();
if (!self.selectedFile) {
return;
}
self.fileInfo = {fileLocation: self.folderPath + self.selectedFile};
FileService.detectFileDelimiter(self.fileInfo)
.then(
function ( fileDelimiter ) {
//do something
},
function( errResponse ) {
self.displayError = "Error attempting to detect file delimiter";
}
)
.then(function finishUp(response){
console.log("returning from detectDelimeter");
})
;
deferred.resolve("Detect Delimeter");
deferred.promise;
}
Now I am trying to synchronise these 2 functions F1 and F2 and make third function call:
self.updateSelectedFile = function ()
{
self.setRecordCount()
.then(function(){
console.log("promise done : setRecordCount")
self.detectDelimiter()
.then(function(){
console.log("promise done : detectDelimiter")
self.generateFilePreviewInfo();
})
})
}