javascript - Calling done on an array of http.get requests in Node.js -
i have array of urls i'm using loop call http.get requests. since async process, i'd call done after requests have returned.
here current attempt:
grunt.registertask('verify', function() { var done = this.async(); var promises = []; var urlprefix = 'http://example.com/'; for(var = 0; < deployablefiles.length; i++) { (function(i) { var deferred = q.defer(); promises.push(deferred); var file = deployablefiles[i]; var path = file.filetype + '/' + getversionedfilename(file.basename, file.filetype); http.get(urlprefix + path, function(res) { deferred.resolve(); if(res.statuscode === 200) { grunt.log.oklns(path + ' found on production server.'); } else { grunt.log.error('error! ' + path + ' not found on production server!'); } }).on('error', function(e) { grunt.log.error("got error: " + e.message); done(); }); })(i); } q.all(promises) .done(function() { // executed correctly return done(); }, function(reason) { // there error somewhere return done(false); }); });
i'm sure it's me not wrapping head around whole async nature of node correctly, there glaringly obvious else?
i've searched using http q library, , appears might required use q.nfcall work. i'm having trouble seeing why i'd have that. (i'm not adverse doing that, i'm more curious else)
thanks!
you should perform promisification @ lowest level possible. makes reasoning concurrency lot easier.
function getping(url){ return new q.promise(function(resolve,reject){ http.get(url,function(res){ // note _not_ wait whole request // headers. if(res.statuscode === 200) resolve(); else reject(); }); }); }
this let do:
grunt.registertask('verify', function() { var done = this.async(); var urlprefix = 'http://example.com/'; var pings = deployablefiles.map(function(file){ var path = file.filetype + '/' + getversionedfilename(file.basename, file.filetype); return getping(urlprefix + path); }); q.all(pings).then(done).catch(function(reason) { // there error somewhere // happen _one_ promise rejected return done(false); }); });
this can further shortened using better promise library bluebird.
Comments
Post a Comment