0

I'm trying to use await on var application = await SchedulerService().getIssues(issueId)

And it returns the error: SyntaxError: await is only valid in async function

I'm starting in node.js. What can I do to fix it?


I've tried already

  • Add async before initial function const SchedulerService = await function(){ at line 1

  • Add async on first return return async () => { where's return { at line 3


import schedulerConf from '../../config/scheduler';
import authConf from '../../config/auth';
import applicationConf from '../../config/application';
import request from 'request';
import schedule from 'node-schedule';
import dateformat from 'dateformat';

let interations = 0;
var serviceRecords = [];
var issueRecords = [];

const SchedulerService = function(){

    return {

        initialize: async () => {
            console.log(`***** Starting Scheduler on ${dateformat(new Date(), "dd/mm/yyyy HH:MM:ss")}`);
            var j = schedule.scheduleJob('*/1 * * * *', function(){
                console.time('└─ Scheduler execution time');
                if(interations === 0){
                    console.log(`Setting scheduler runtime to full time.`);
                }else{                    
                    console.log(`------------------------`);
                }
                interations++; 
                console.log(`Job execution number: ${interations}.`);

                SchedulerService().execute()
                .then(response => { 
                    console.log(`└─ Job ${interations} was successfully executed.`);
                    console.log(`└─ Execution date ${dateformat(new Date(), "dd/mm/yyyy HH:MM:ss")}`);
                    console.timeEnd('└─ Scheduler execution time');
                }).catch(error => { 
                    console.log(`└─ Job ${interations} returned error while executing.`);
                });

            });

        },

        execute: async () => {             

            return  SchedulerService().getRecords2Sync()            
                    .then(() => {
                        SchedulerService().sync().then(() => {
                        }).catch(error => {console.log({error})});
                    }).catch(error => {console.log({error})});

        },

        getRecords2Sync: async () => {
            serviceRecords = [];
            var options = {
                url: `http://localhost:${authConf.serverPort}/application`,
                method: 'GET',
                headers: {
                    authorization: `${authConf.secret}`
                }
            }              
            return new Promise(function (resolve, reject) {
                request(options, function (error, res, body) {
                    if (!error && res.statusCode == 200) {
                        const srs = JSON.parse(body);                        
                        const response = srs['response'];
                        for(let i =0;i < response.length;i++){
                            const { id, info } = response[i];
                            var status = "";
                            var issueId = "";
                            var statusClass = "";
                            for(let x = 0; x < info.length; x++){
                                if(info[x].key === "status"){
                                    status = info[x].value;
                                    statusClass = info[x].valueClass;
                                }
                                if(info[x].key === applicationConf.fields.issueId){
                                    issueId = info[x].value;
                                }
                            }
                            if(statusClass === 0){ 
                                if(issueId !== null && issueId !== ""){ 
                                    serviceRecords.push({id, status, issueId});
                                }
                            }
                        }
                        //console.log(serviceRecords);
                        resolve(serviceRecords);
                    } else {
                        //console.log(error);
                        reject(error);
                    }
                });
            });    
        },

        getIssues : async (issueId) => { 
            issueRecords = [];     
            return new Promise(function(resolve, reject) {                                 
                var options = {
                    url: `http://localhost:${authConf.serverPort}/application2/${issueId}`,
                    method: 'GET',
                    headers: {
                        authorization: `${authConf.secret}`
                    }
                }            
                request(options, function(error, res, body) {
                    if (!error && res.statusCode == 200) {

                        const issues = JSON.parse(body);                     
                        const { issue } = issues.response;
                        const { id, status, custom_fields  } = issue;

                        issueRecords.push({id, status, custom_fields});                                       
                        resolve(issueRecords);

                    } else {
                        reject(error);
                    }
                });   
            }); 
        },

        sync : async () => { 
            return new Promise(function(resolve, reject) {

                for (let i = 0; i < serviceRecords.length; i++) { 

                    const application_id = serviceRecords[i].id;        
                    const application_status = serviceRecords[i].status;        
                    const application_issueId = serviceRecords[i].issueId;

                    //console.log('issueRecords.length: ', issueRecords);
                    //console.log('issueRecords.length: ', issueRecords.length);

                    console.log(`********** application`);
                    console.log(`└─ id ${application_id}`);
                    console.log(`└─ status ${application_status}`);
                    console.log(`└─ issueId ${application_issueId}`);

                    var application2 = await SchedulerService().getIssues(application_issueId)
                                        .then(response => {
                                            resolve(() => {
                                                console.log(`i've found a record by issue_id ${application_issueId}`);
                                            });
                                        }).catch(error => {
                                            reject(error);
                                        });


                }
            }); 
        }

    }


}

export default new SchedulerService();

Thank you so much!

Leonardo
  • 135
  • 1
  • 2
  • 11
  • 4
    The `await SchedulerService().getIssues` is inside the function given to the promise constructor - `new Promise(function(resolve, reject)` - *that* one needs to be async for the await to be valid. However, [it doesn't seem like it's very good design to give a promise an async function](https://stackoverflow.com/questions/43036229/is-it-an-anti-pattern-to-use-async-await-inside-of-a-new-promise-constructor). You probably need to re-jig your code. – VLAZ Sep 11 '19 at 13:47
  • @VLAZ, Thanks, You're right, reorganize seems to be the best way, but I don't know how to do that. – Leonardo Sep 11 '19 at 13:51
  • It's not clear where that `issueId` is coming from. Is it meant to be `serviceRecords[i]`? – Andy Sep 11 '19 at 13:51
  • @Andy, I just updated, and paste all the code - sorry, I missed some parts. – Leonardo Sep 11 '19 at 13:56

1 Answers1

0

If you had getIssues resolve with issueId and issueRecords you might do something like this in sync:

sync: async () => {

  // `map` over the serviceRecords and return a getIssues promise for each issueId
  const promises = serviceRecords.map(({ issueId }) => SchedulerService().getIssues(issueId));

  // Wait for all the promises to resolve
  const data = await Promise.all(promises);

  // Loop over the resolved promises and log the issueId
  data.forEach((issueId, issueRecords) => console.log(issueId));
}
Andy
  • 61,948
  • 13
  • 68
  • 95