我已經完成了learnyounode這個練習,我試圖用ES2015的promise(或者如果更簡單的話與其他庫)重構它。我已閱讀了許諾,並且我想我理解他們的工作方式,但是我想知道是否可以在以下代碼中使用它們以及如何執行它。使用Promises而不是回調
我的目標是讓代碼更易於閱讀和理解,並更好地理解過程中的承諾。
let http = require("http");
if (process.argv.length != 5) {
throw new Error("Please provide the 3 URLs as a command line arguments");
}
let urls = [];
let results = [];
let count = 0;
for (let i = 2; i < process.argv.length; i++) {
urls.push(process.argv[i]);
}
function httpGet(index) {
let url = urls[index];
let result = "";
http.get(url, res => {
res.on("data", data => {
result += data;
});
res.on('end',() => {
count += 1;
results[index] = result;
if (count === 3) {
results.forEach(function(result) {
console.log(result);
});
}
});
});
}
for (let i = 0; i < urls.length; i++) {
httpGet(i);
}
根據[文檔](https://nodejs.org/api/http.html#http_http_get_options_callback)'http.get'不返回承諾並僅支持回調方法。你將不得不自己創造和解決承諾。 – Cristy
bluebirds如何對上面的代碼提供幫助?*答案:根本沒有* –