这是您要用于普通回调样式的基本模式:
function getwebsite(url, cb) {
var body = "";
http.get(url, function (res) {
res.on('data', function (chunk) {
body += chunk.toString();
// you can't return a value from this function
// the return value would be swallowed by the function
// that is calling this function
// which is not your code, but internal Node.js code
});
res.on("end", function() {
cb(null, body)
})
res.on("error" function(error) {
cb(error)
})
});
}
getwebsite("a", function(error, contentsA) {
if (error) throw "Error getting website A."
getwebsite("b", function(error, contentsB) {
if (error) throw "Error getting website B."
console.log(contentsA)
console.log(contentsB)
})
})
You may also want to look into flow-control libraries like Async (or my promise-based Faithful), or general-purpose promise libraries like RSVP.js.
I recommend first getting accustomed with the basics of callbacks though.
For simple http requests, it's much easier to use the request module. You won't have to bind event listeners then. You just have a function that you can use in a similar way to the getwebsite
function (which has issues!).
To get acquainted with async programming, you may want to try reading and writing some files with fs.readFile
and fs.writeFile
. For example, try to write contents of file A to file B. These are pretty simple functions, but you need to handle the callback-flow right. Node's http module is relatively complex in comparison. Or use the request module for that, as I mentioned.