node.jspromiseasync-awaitnode-schedule

Return Promise after job execution in Node.js


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);
   });
}

Solution

  • 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);  
               }
           });
       });
    }