1
我已經制作了一個nodejs腳本來將css文件上傳到我們的Web應用程序。我省略了一切,沒有必要:將回調轉換爲nodejs中的承諾
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()
函數將異步調用。
我知道這可以做得更清潔承諾,但我不知道從哪裏開始?
FWIW,並不是所有人都認爲一切都更清晰,有保證。我實際上是async.js對你所談論的各種事物的忠實粉絲。 – Paul
你有沒有看過[如何將現有的回調API轉換爲承諾?](http://stackoverflow.com/q/22519784/1048572)請嘗試一下。 – Bergi