1

I have made a nodejs script to upload css files to our web application. I've omitted everything that's not necessary:

var downloadCSS = function() {
  var download = wget.download(src, output, options);
  download.on('end', function(outputMessage) {
    var unzipStream = fs.createReadStream(output).pipe(unzip.Extract({ path: path }));
    unzipStream.on('close', function() {
      findFilesAsync(path);
    });
  });
}

var findFilesAsync = function(path) {
  for (var vendor in searchList) {
    (function(filePath, vendor, loginCredentials){
      glob(filePath, function(err, files) {
        login(loginCredentials, files[0], vendor);
      })
    })(filePath, vendor, loginCredentials);
  }
};

var login = function(credentials, file_local, vendor) {
  request.post(
    'https://server', 
    function(error, response, body) {
      getSettings(cookie, file_local, vendor);
    }
  );
};

var getSettings = function(cookie, file_local, vendor) {
  request.get(
    'https://server', 
    function(error, response, body) {
      fileUpload(cookie, settings, file_local, vendor);
    }
  );
};

var fileUpload = function(cookie, settings, file_local, vendor) {
  var CSS_file = fs.createReadStream(file_local);

  CSS_file.on('error', function(err) {
    console.log('error at reading CSS file');
  });

  request.post(
    'https://server', 
    function(error, response, body) {
      setSettings(cookie, settings, vendor);
    }
  );
};

var setSettings = function(cookie, settings, vendor) {
  request.put(
    'https://server',
    function(error, response, body) {
      logout(cookie, settings, vendor);
    }
  );
};

var logout = function(cookie, settings, vendor) {
  request.get(
    'https://server', 
    function(error, response, body) {
    }
  );
};

To upload a css file the functions get called top to bottom if there is no error:

downloadCSS()
findFilesAsync()
login()
getSettings()
fileUpload()
setSettings()
logout()

There are 5 CSS files, so whenever a file is found in the findFilesAsync() function, a new login() function will be called asyncronously.

I know this can be done cleaner with promises, but I don't know where to start?

mles
  • 4,534
  • 10
  • 54
  • 94
  • 2
    FWIW, not everyone agrees that everything is cleaner w/ promises. I am actually a big fan of async.js for the kinds of things you're talking about. – Paul Apr 19 '16 at 13:47
  • Have you had a look at [How do I convert an existing callback API to promises?](http://stackoverflow.com/q/22519784/1048572) Please try something. – Bergi Apr 19 '16 at 14:02

1 Answers1

0

Take a look at this MDN Promise reference they have given a nice example function for http requests that uses promises. So in order to avoid callbacks you will have to change/modify your request class

Teneff
  • 30,564
  • 13
  • 72
  • 103