I have this code below which is not working as I am expecting.Here GetAllFileNames is Async function and I want to do some sequential action based on result of this funciton. So I am using Jquery promise. But I feel that statement return deferred.resolve(GetAllFileNames)
is not correct.It immediately calls promise.then
without even waiting for GatAllFileNames to finish.Please note this is not actually working code.
function getfilenames() {
var deferred = $.Deferred();
if(condition == true) {
return deferred.resolve(JSON.parse(allFileNames));
} else {
return deferred.resolve(GetAllFileNames());
}
}
var promise = getfilenames();
promise.then(function(fileNames) {
result.fileNames = fileNames;
});
UPDATE: I tried some of your comments ,but none of them is working.Here is one of example which is not working
<!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(function () {
var deferred = $.Deferred();
var result = {};
var GetAllFileNames = function () {
return {
"allFileNames": [1, 2, 3, 4, 5, 6, 7, 8, 9]
};
};
function getfilenames(condition) {
if (condition == true) {
return deferred.notify(JSON.parse(allFileNames));
} else {
return deferred.notify(GetAllFileNames());
}
};
deferred.then(
// `deferred.done`
function (fileNames) {
result.fileNames = fileNames;
$("<span>" + result.fileNames.allFileNames + "</span>")
.appendTo("body"); console.log(JSON.stringify(fileNames));
}
// `deferred.fail`
,
function () {
console.log(new Error("getfilenames error").message);
} );
getfilenames(false);
}) </script> </head> <body>
</body> </html>