2

I´m creating a small Node.js application for some monitoring stuff. The following operation has to be made with this app:

A job scheduler (using node-schedule module) is retrieving data from a web service within a time period and inserting the content into an array (for further processing). After finishing the job a promise should resolve the complete array in order to use it in my main program.

Here is my coding so far. With this coding the promise gets resolved before finishing the job and the array is empty. Can you give me any hints how to solve this?

async function dataRetrieval(start, end, rule){
   let array = [];
   return new Promise(function (resolve) {
       schedule.scheduleJob({start: start, end: end, rule: rule}, async function (){
           let data = await service.getData();
           array.push(data);
       });
       resolve(array);
   });
}
stefano
  • 315
  • 2
  • 16

2 Answers2

2

The problem is that you are resolving it outside the callback completion. You need to resolve it inside the callback.

Something like this

async function dataRetrieval(start, end, rule){
    let array = [];
    return new Promise(function (resolve) {
        schedule.scheduleJob({start: start, end: end, rule: rule}, async function (){
            let data = await service.getData();
            array.push(data);
            resolve(array);
        });
    });
 }
Ashish Modi
  • 7,529
  • 2
  • 20
  • 35
  • Thanks for your hint too! Actually the answer above suits better for me, but thank you for your effort and time! – stefano Feb 20 '20 at 07:50
2

This is happening because scheduleJob is an asynchronous function, and your resolve call takes place outside of your callback, before the job is finished.

You can use the fireDate value that is passed to the callback from scheduleJob to check if the current execution is the last one. If so, only then, you call resolve with the final data from the callback:

async function dataRetrieval(start, end, rule){
   let array = [];
   return new Promise(function (resolve) {
       schedule.scheduleJob({start: start, end: end, rule: rule}, async function (fireDate) {
           let data = await service.getData();
           array.push(data);

           if (fireDate >= end) {
               resolve(array);  
           }
       });
   });
}
Alberto Trindade Tavares
  • 10,056
  • 5
  • 38
  • 46
  • 1
    Thank you for your answer. This was the hint and after some modification I´ve got it working! Thumbs up! – stefano Feb 20 '20 at 07:49