I've encountered some challenges with Promises and I'm curious to delve deeper into how they operate. In my current project, I'm utilizing the Bookshelfjs ORM to retrieve data from Postgres.
The code snippet below represents my current focus. For this request, I receive an array of device IDs, each corresponding to a device operating in one of two modes.
router.post('/devices', function (req, res, next) {
var currentData = [];
var deviceIds = req.body.devices;
loadash.forEach(deviceIds, function (device) {
var deviceid = device.deviceid;
Device.forge()
.where({deviceid: deviceid})
.fetch({columns: ['id', 'mode']})
.then(function (fetchedDevice) {
if(fetchedDevice.get('mode') === 1) {
Model_1.forge()
.where({device_id: fetchedDevice.get('id')})
.orderBy('epoch_time', 'DESC')
.fetch()
.then(function (modelOne) {
//first push
currentData.push(modelOne.toJSON());
//array with first push data
console.log(currentData)
})
.catch(function (err) {
console.log(err);
});
}
else if(fetchedDevice.get('mode') === 2) {
Model_2.forge()
.where({device_id: fetchedDevice.get('id')})
.orderBy('epoch_time', 'DESC')
.fetch()
.then(function (modelTwo) {
//second push
currentData.push(modelTwo.toJSON());
//array not empty here(shows data from both push)
console.log(currentData);
})
.catch(function (err) {
console.log(err);
});
}
})
.catch(function (err) {
console.log(err);
});
});
//This shows an empty array
console.log('Final: ' +currentData);
});
Asynchronous behavior in Javascript is likely causing the issue that results in an empty array being displayed. My questions are:
How can I display the final array after all
push()
operations have been completed? I attempted using thePromise.all()
method without success.Is it feasible to extract
modelOne
ormodelTwo
from each promise and then add them to an array? How can I achieve this?