i have method in 1 of controller. purpose of controller, print array of urls using webshot package.
this code in question:
router.post('/capture', function (req, res, next) { //check params remove var json = json.parse(req.body.data); var promise = new promise(function (resolve, reject) { var totalimages = object.keys(json).length; var arraylisturlimages = new array(totalimages); var counter = 0; var completedir = dir + ''; //directory url (var value of json) { var url = 'http://example.com/' + id + '/' + value.anothervalue; var folder = completedir + id + '/' + value.anothervalue + '.jpg'; //options capturing image var options = { renderdelay: 1000, quality: 100, phantomconfig: { 'local-to-remote-url-access': 'true', 'ignore-ssl-errors': 'true' } }; var anothervalue = value.anothervalue; (function (anothervalue) { webshot(url, folder, options, function (err) { // screenshot saved if (err === null) { var urlimage = "http://example.com/images/" + id + "/" + anothervalue + ".jpg"; arraylisturlimages.push(urlimage); counter++; console.log("counter: " + counter); if (counter === totalimages) { resolve(arraylisturlimages); } } else { reject(err); } }); })(anothervalue); } }).then(function (arrayimages) { res.send(arrayimages); }).catch(function (errorvale) { res.send(null); }); });
this code working without problems... better. don't know how many urls need check (this important detail because need each or similar).
i have read async package... better option move code async.parallel? can use yield in code?
thanks!
this example of code flow based on inner functions:
router.post('/capture', function (req, res, next) { // definitions // load image function loadimage(value) { var url = 'http://example.com/' + id + '/' + value.anothervalue; var folder = completedir + id + '/' + value.anothervalue + '.jpg'; //options capturing image var options = { renderdelay: 1000, quality: 100, phantomconfig: { 'local-to-remote-url-access': 'true', 'ignore-ssl-errors': 'true' } }; return webshotpromise(url, folder, options); } // load whebshot promise function webshotpromise(url, folder, options) { return new promise((resolve, reject) => { webshot(url, folder, options, function (err) { if (err) { reject(err); } var urlimage = "http://example.com/images/" + id + "/" + anothervalue + ".jpg"; resolve(urlimage); } }); } // method flow const json = json.parse(req.body.data); // json keys , iterate on load promise.all( object.getownpropertynames(json).map(key => loadimage(json[key])) ) // got list of urls .then((list) => { res.json(list); }, (error) => { console.error(error); res.json(null); }); });
Comments
Post a Comment