So I was solving this learnyounode
exercise called Juggling Async , which basically gives me 3 URLs and asks me to output the URL content, in the order of the URLs input.
I came up with a recursive solution, in which a callback calls another callback while maintaining an exit counter num
. However, when I run this, I keep getting blank lines on the console, no matter what the input.
This is the short code:
var url = ["", process.argv[2], process.argv[3], process.argv[4]];
var http = require('http');
var str = ["", "", "", ""];
var cnt = 1;
function dos(num, callback)
{
if(num == 4)
return;
http.get(url[num], function (response1){
// console.log(num);
response1.setEncoding('utf8');
response1.on('data', function(data1) {
str[num] = data1;
callback(num + 1, dos);
})
});
}
dos(1, dos);
console.log(str[1]);
console.log(str[2]);
console.log(str[3]);
Now, this is my first time pulling off recursion with callback functions. I learned callback functions just two days ago, which might mean that there is something glaringly wrong here which I cannot see. Please help me see. Thank you.
Look at the execution order.
dos
function dos
function console.log
The problem with your code is asynchronous nature of the http.get
method.
In the definition of dos
whenever http.get
is invoked, a callback is attached and after that control flow exists the function scope. Control flow is not stopping and waiting for the get
call to complete.
It exits the function scope and moves onto invoking console.log
so you get blank strings because that's what your array contains at that moment.
For you to achieve your expected result.
In the function call instead of assigning the value of data1
to str[num]
. Do a simple console.log(data1)
in place.
If you still prefer the outside console.log
placement in your code. You read about async\\await
.
dos
invokation must return a Promise
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.