Proper chaining of File plugin promises


#1

There are many async methods in the File plugin.

If I want to do a series of file operations one after another in sequence, how should I chain them correctly?

For example, if I want to:

  1. Create a file
  2. Check the newly created file exists
  3. Write to the file.
  4. Read its content as text.

In the normal synchronous world, it would be just calling them in sequence in a new line like the following pseudocode:

var createOk = $cordovaFile.createFile(path, file, true);
var exists = $cordovaFile.checkFile(path, file);
var writeOk = $cordovaFile.writeFile(path, file, "The quick brown fox jumps over the lazy dog.\n", true);
var text = $cordovaFile.readAsText(path, file);

In the Javascript promise style, how should this be done? Do I stick a subsequent step as a parameter (function) in the then() method call? Does this look like a callback hell?

$cordovaFile.createFile(path, file, true).then(
  function(success){
    $cordovaFile.checkFile(path, file).then(
      function(success){
        $cordovaFile.writeFile(path, file, "The quick brown fox jumps over the lazy dog.\n", true).then(
          function(success){
            $cordovaFile.readAsText(path, file).then(
              function(success){
                console.log("I am finally done.");
              }
            );
          }
        );
      }
    )
  }
);

Or more of the following? I am not sure how the derived promises are formed. From the returned value of the previous success function? Of the return value becomes the input for the next resolve function as success parameter?

$cordovaFile.createFile(path, file, true).then(
  function(success){
    return $cordovaFile.checkFile(path, file);
  }
).then(
  function(success){
    return $cordovaFile.writeFile(path, file, "The quick brown fox jumps over the lazy dog.\n", true);
  }
).then(
  function(success){
    return $cordovaFile.readAsText(path, file);
  }
).then(
  function(success){
    console.log("I am finally done.");
  }
);

Sorry, I am not familiar with Javascript promise and $q.

I have an existing code that does not chain the promises and the asynchronous operations are all jumbled out of sequence e.g. the file check starts before the file creation is done. Trying to figure out the right way to use promises elegantly.