将回调转换为nodejs中的promise

时间:2016-04-19 13:44:09

标签: javascript node.js callback promise

我已经创建了一个nodejs脚本来将css文件上传到我们的Web应用程序。我省略了一切不必要的东西:

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) {
    }
  );
};

要上传css文件,如果没有错误,函数会从上到下调用​​:

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

有5个CSS文件,因此只要在findFilesAsync()函数中找到文件,就会异步调用新的login()函数。

我知道这可以通过承诺更清洁,但我不知道从哪里开始?

1 个答案:

答案 0 :(得分:0)

看一下这个MDN Promise reference,他们为使用promises的http请求提供了一个很好的示例函数。因此,为了避免回调,您必须更改/修改request