here example of working code:
request('http://foo.com/') // collect list of locations. .then(function (response) { let $ = response.data, locations = []; $('a[href^="/venues/"]').each(function () { locations.push({ name: $(this).text(), url: 'http://foo.com/' + $(this).attr('href') }); }); return locations; }) // retrieve additional information locations. .map((location) => { return request(location.url) .then((response) => { // combine location specific information initial location information. response; location; }); }, { concurrency: 5 });
in above example, making request "foo.com", list of locations, use location data query "foo.com" additional information location. @ end, combine location specific information initial location information.
what not above above code is not flat. if location specific query require additional async information , child require more additional async information, code turn callback hell.
i turn code flat structure, e.g. (pseudo-code)
request('http://foo.com/') // collect list of locations. .then(function (response) { let $ = response.data, locations = []; $('a[href^="/venues/"]').each(function () { locations.push({ name: $(this).text(), url: 'http://foo.com/' + $(this).attr('href') }); }); return locations; }) // retrieve additional information locations. .map((location) => { return request(location.url); }, { concurrency: 5 }) // filter list of responses. .filter((response) => { return response.incomingmessage.statuscode === 200; }) // combine location specific information initial location information. .map((response) => { // how access "location" , "response"? });
what best way achieve it?
the way think of doing augmenting response of request additional data location, e.g.
.map((location) => { return request('http://foo.com/' + location.nid) .then((response) => { return { location: location, response: response }; }); }, { concurrency: 5 })
this way entire promise chain remains more or less flat.
request('http://foo.com/') // collect list of locations. .then(function (response) { let $ = response.data, locations = []; $('a[href^="/venues/"]').each(function () { locations.push({ nid: $(this).attr('href'), name: $(this).text(), url: 'http://foo.com/' + $(this).attr('href') }); }); return locations; }) // retrieve additional information locations. .map((location) => { return request('http://foo.com/' + location.nid) .then((response) => { return { location: location, response: response }; }); }, { concurrency: 5 }) // filter list of responses. .filter((response) => { return response.response.incomingmessage.statuscode === 200; }) .map((response) => { // combine location specific information initial location information. response.response; response.location; });
Comments
Post a Comment