javascript - How to return promise up the chain after recursion -
i making request returns paged data, want call function recursively until have of pages of data, so:
router.get("/", (req, res) => { dorequest(1, []) .then(result => { res.status(200).send(result); }) .catch(error => { console.error(error); res.status(500).send("error request"); }); }); function dorequest(page, list){ let options = { uri : "www.example.com", qs : { "page" : page } }; request(options) .then((results) => { list.push(results); if(page === 2){ return promise.resolve(list); } else { return dorequest(++page, list); } }) .catch((error) => { return promise.reject(error); }); }
my route returning cannot read property 'then' of undefined
, dorequest()
apparently returning undefined
right away, rather returning list when ready. i'm new promises i'm sure i'm missing pretty simple.
change dorequest
function to
function dorequest(page, list){ let options = { uri : "www.example.com", qs : { "page" : page } }; return request(options) .then((results) => { list.push(results); if(page === 2){ return promise.resolve(list); } else { return dorequest(++page, list); } }) .catch((error) => { return promise.reject(error); }); }
so can return request, returns nothing (undefined
)
Comments
Post a Comment