node.js - JavaScript callback vs return -
I have a JavaScript (node) function to handle the content of a Web page and handle it with callback: I do not understand why I can not just return results at 'end'. Clearly, when the 'end' event is emitted, the 'content' variable contains a string with the content of a web page, otherwise it can not be submitted to the callback function, so why not I return it like this Can: d Why download 2 always undefines? These are asynchronous tasks before they are called Callback Functions So, the desired return result is not known when any of your downloading works returns returns. For asynchronous data passed to the callback, in one place only you can do something with that data callback That's the callback that day Defense can put your code to handle or you can call another function from within the callback and data to it. It is asynchronous programming and you really have to use it in the node because it used a lot there, it is very different from synchronous programming in which you can not call a function that is an asynchronous operation Start and expect the original work to get results and return it. The result of the asynchronous operation will not be known for a while, after the original work has been returned. In this way, the way you downloaded it in your first 'Strict use'; Var http = Required ('http'); Function download (url, callback) {http.get (url, function (rij) {var content = ''; res.on ('data', function (chuck) {content + = chunk;}); res.on 'End', function () {callback (content);});}) ('error', function () {callback (tap);}); }
function download2 (url) {http.get (url, function) {var content = ''; res.on ('data', function (part) { Content (+);); res.on ('end', function () {return content;})}}. ('Error', function () {return null;});}
() function is a simple way of handling it.
Comments
Post a Comment