Friday, 4 October 2019

iterating asynchronously with async.eachSeries

I know this is a common problem for people, and I've looked up some guides and looked at the docs, but I'm not understanding what is happening, and would love some help.Her is the controller function I am working on:appRepo.findWithId(req.params.id, (err, myApp) => { if (err) { console.log(err) } let devices = myApp.devices let devicesDataArray = [] // construct object to be returned let appsDataObject = { name: myApp.name, user_id: myApp.user_id, devices: devicesDataArray, permissions: myApp.permissions } async.eachSeries(devices, function (device, eachCb) { deviceRepo.findById(new ObjectID(device), (err, myDevice) => { if (err) { eachCb(err) } // get/construct device data, push to object to be returned let deviceObj = { name: myDevice.name, version: myDevice.version } appsDataObject['devices'].push(deviceObj) }) eachCb(null) }, function (err) { if (err) console.log(err) }) console.log(JSON.stringify(appsDataObject) + ' || apps data obj before return') return res.status(200).send(appsDataObject) }) } I originally wrote this with a for loop and a callback, but I think it was impossible to do that way (I'm not sure about that though). Pretty much all my experience is with older code using callbacks, not promises or an async library, so I'm out of my element, although I'm told this is the better way to do it.As I understand it, anything before the eachCb(null) line will be repeated in the loop. But where my return statement is now, it returns too quickly, and appsDataObject.devices is an empty array. I've also the return statement inside the callback, but that also results in an empty array for appsDataObject.devices. Where should the return statement go in this situation?I'm not understanding how these async functions are supposed to work, can someone please help me understand? Thank you.

Submitted October 04, 2019 at 06:01PM by Briyo2289

No comments:

Post a Comment