Can't figure out promises, need some tips/guidance

So I’m trying to wrap my head around promises and using them but having little luck there. Right now I’m using this fileExists function which is linked to a button

// Called to check file
$scope.fileExists = function(filename) {
  var rs = '';
  var folder = "";
  fileService.checkFile(folder, filename).then( 
  	function(data){
		console.log(data);
		rs = data;
	}
  );
  console.log(rs);
};

It’s calling this checkFile function I got from github

checkFile: function (dir, file) {
var deferred = $q.defer();

        getFilesystem().then(
            function(filesystem) {
                filesystem.root.getFile('/'+ dir +'/'+ file, {create: false}, 
                    function() {
                        //File exist
                        deferred.resolve();
                    },
                    function() {
                        //File dont exist
                        deferred.reject();
                    }
                );
            }
        );
                
        return deferred.promise;
    }

My main questions are how do i detect resolve and reject, how can I set a variable in then, success, error methods properly, and how do I handle promise objects in general?

I’ve tried setting a variable within then, success, or error but it turns up blank on the log. Which means to me that everything is getting finished before it gets to that point.

I’ve googled the issues I’m having but everything is too vague or is similar to what I want to do but it just doesn’t work.

A couple reasons you are seeing nothing in your console.

When fileExists is executed, the order of execution is:

  1. Calls checkFile, which returns a promise
  2. Calls console.log(rs); which returns ‘’ since the “then” part of your function isn’t executed yet.
  3. Once the getFile function resolves the promises, your “then” function will run. Since the promise isn’t resolved with anything, your “data” parameter will be undefined, that is why your other console.log will be empty.

As long as your “then” function is executed, it means the file exists. To check if the file doesn’t exist, you need to add a catch function:

fileService.checkFile(folder, filename)
.then(function () {
    console.log('File Exists');
})
.catch(function () {
    console.log('File Does Not Exist');
});
function funcDelayed() {
    var deferred = $q.defer();

    setTimeout(function() {
        deferred.resolve('this message is returned after 1000 milliseconds');
    }, 1000);

    return deferred.promise;
}

funcDelayed().then(function (returnValue) {
  //resolved
  console.log(returnValue); 
}, function (returnValue) {
  //rejected
});

How simple promises work is like above. You have a function (example funcDelayed), which creates a promise object using $q.defer() and stores it in a variable called deferred. At the end of the function, the promise object is returned.

You then call this function (at the bottom of the code here) and it’ll return the promise object. The promise object has a then method, to which you pass two functions. The first is the ‘resolve’ function, the second the ‘reject’ function.

Back in the promise function, I set a timer for 1000 ms, after which it’ll run deferred.resolve();. This is another method of the promise object we created. When you run it and pass a value into it, it’ll run the resolved function I mentioned earlier (which is a console.log of the message we pass).

We can also reject the promise which I didn’t do, by calling deferred.reject() instead of .resolve().

An example could be say downloading a large file. If the download is complete you run .resolve inside the downloading function and pass it say the downloaded file as the parameter, if the download failed you run .reject and pass it say an error message of what went wrong (e.g. server went down, no diskspace, whatever). You then call the download function, and run the .then() method on it and pass a function for when the download succeeds, and when it fails. (e.g. display the contents of the file, and tell the user about the error, respectively)

https://docs.angularjs.org/api/ng/service/$q

Let me know if you need any more help.

1 Like