Вы можете получить желаемый результат с помощью более простого кода.
Я переписал finalData
с помощью созданной мной библиотеки, rubico . rubico удаляет множество шаблонов, окружающих промисы.
const { pipe, fork, tryCatch, switchCase, map, get, gt } = require('rubico')
const identity = x => x
const findDevices = () => new Promise((resolve, reject) => {
Device.find((err, data) => err ? reject(err) : resolve(data))
})
const getLocationByDeviceID = deviceId => new Promise((resolve, reject) => {
Location.findOne(
{ device: deviceId },
(err, data) => err ? reject(err) : resolve(data),
).sort({ _id: -1 })
})
const getDeviceInfoByDeviceID = deviceId => new Promise((resolve, reject) => {
DeviceInfo.findOne(
{ device: deviceId },
(err, data) => err ? reject(err) : resolve(data),
).sort({ _id: -1 })
})
const getDailyStatusByDeviceID = deviceId => new Promise((resolve, reject) => {
DailyStatus.findOne(
{ device: deviceId },
(err, data) => err ? reject(err) : resolve(data),
).sort({ _id: -1 })
})
const finalData = pipe([
tryCatch(
findDevices, // try findDevices()
() => { throw new Error('error in sending the data') }, // on error, throw a new Error
),
switchCase([
gt(get('length'), 0), identity, // if data length is greater than 0, send it through (x => x)
() => { throw new Error('data length is ! > 0') }, // else throw a new Error
]),
map(fork.series([ // for each device, log speed, ignition, dailyStatus in series
pipe([
get('deviceId'), // device => device.deviceId
getLocationByDeviceID, // deviceId => getLocationByDeviceID(deviceId) => location
get('speed'), // location => location.speed
x => console.log(x, 'dataSpeed')
]),
pipe([
get('deviceId'), // get device.deviceId
getDeviceInfoByDeviceID, // deviceId => getDeviceInfoByDeviceID(deviceId) => deviceInfo
get('ignition'), // deviceInfo => deviceInfo.ignition
x => console.log(x, 'dataIgnition')
]),
pipe([
get('deviceId'), // get device.deviceId
getDailyStatusByDeviceID, // deviceId => getDailyStatusByDeviceID(deviceId) => dailyStatus
get('status'), // dailyStatus => dailyStatus.status
x => console.log(x, 'dataDailyStatus')
]),
])), // [device] => [{ speed, ignition, status }]
])
cron.schedule('*/1 * * * * *', finalData)