node.js - learnyounode #9 juggling async, can official solution break? -
so learning node.js right , have done multitasking before , concept async , multitasking have many similar isses, brings me question.
the official solution problem is:
var http = require('http') var bl = require('bl') var results = [] var count = 0 function printresults () { (var = 0; < 3; i++) console.log(results[i]) } function httpget (index) { http.get(process.argv[2 + index], function (response) { response.pipe(bl(function (err, data) { if (err) return console.error(err) results[index] = data.tostring() //area of interest start count++ if (count == 3) printresults() //area of interest end })) }) } (var = 0; < 3; i++) httpget(i)
notice part in 'area of interest' comments. not possible race condition occur here causing printresults function called multiple times?
for example, 3 'end' callbacks come simultaneously, each executes count++
1 after other (so count == 3
check has not happened yet on callback count has been increment thrice) each of them check count == 3
condition, true calling printresults
thrice
is possible , official solution flawed or misunderstanding concepts?
no, race condition not problem code. callbacks run in single thread. not run @ once in parallel. run in series.
for more information on how callbacks queued , why there no race condition in code, may choose watch a great video philip roberts called "what heck event loop anyway?".
Comments
Post a Comment