javascript - nodeschool exercise solving with promises -
i solving nodeschool exercise "juggling async" , solved this
var http=require("http"); var urls=process.argv.slice(2,process.argv.length); var count=0; var junge=[]; urls.map(function(url,index){ http.get(url,function(response){ var str=""; response.setencoding("utf-8"); response.on("data",function(data){str=str+data}) response.on("end",function(){ junge.push(str); count++; if(index==urls.length-1) junge.map(function(v){console.log(v)}) }); });})
(it works) thinking how exercise looked if used promises? tried this
var http=require("http"); var urls=process.argv.slice(2,process.argv.length); var count=0; var fin=[]; var promise=function(x){ return new promise(function(resolve,reject){ http.get(x,function(response){ response.setencoding("utf-8"); var junge=[]; response.on("data",function(data){ junge.push(data); }); response.on("end",function(){ resolve(junge) }) }) } ) } function printitfgt(x){ var m=promise(x); return m.then(function(response){ fin.pus(response) }) } urls.foreach(function(x,index){ printitfgt(x); if(index==urls.length-1) console.log(fin) })
but code not pass expectation , says failed. in case assume code not work or has bug in fail see. sulution promises then?
erazihel right, you're missing reject
. how wrap promises, put little code inside promise constructor executor function possible, e.g. minimal drop-in fills absence of function supports promises.
also, see no reason not use promise.all
urls in parallel (faster):
promise.all(urls.map(function(url) { return new promise(function(resolve, reject) { var str = ""; http.get(url, function(response) { response.on("data", function(data) { str+=data; }); response.on("end", function() { resolve(str); }); response.error("end", function() { reject(str); }); }); }); })) .then(function(junge) { console.log(junge); }) .catch(function(e) { console.log(e); });
i @ using fetch
, if available.
var console = { log: function(msg) { div.innerhtml += msg + "<br>"; }}; var http = { get: function(u, f) { f({ on: function(name, f) { f(name == "data" && u); }}); }}; var urls=["result1", "result2"]; promise.all(urls.map(function(url,index) { return new promise(function(resolve, reject) { var str = ""; http.get(url, function(response) { response.on("data", function(data) { str+=data; }); response.on("end", function() { resolve(str); }); response.error("end", function() { reject(str); }); }); }); })) .then(function(junge) { console.log(junge); }) .catch(function(e) { console.log(e); });
<div id="div"></div>
Comments
Post a Comment