javascript - resolving values after promise has resolved -
i have code this.. want fetch contents , after have loaded, something. use promise.all , access resolved values later. giving values promise {' content here'}. (see console.log..) gonna use regex extract check type isnt string object no keys? why?
var request=require('request'); var urls=['someurl','someurl2','someurl3']; var contents=[]; urls.foreach(function (u) { contents.push(getcontent(u) ); }); promise.all(contents) .then(function () { // should loaded now? // promises resolved fulfiled, , values can accessed later right? contents.foreach(function (promise) { var content = promise.resolve(promise); console.log(content); // promise {'test'} ?? console.log(typeof content,object.keys(content)); // object [] ??? }); }). catch(function(err) { //handle error here }); function getcontent(url) { return new promise ( function (resolve,reject) { /** commented , stripped out testing request(url, function (err,response, data) { if(err) { reject(error(err)); } }); **/ resolve("test"); }); }
contents
still holds promises.
can never directly extract value of promise; can consume then()
callback.
instead, promise.all()
return promise for array of results.
change then()
call take array callback parameter , use directly.
Comments
Post a Comment