无法识别时如何使用等待?

时间:2019-09-11 13:44:28

标签: javascript node.js async-await request sequelize.js

我正在尝试在await上使用var application = await SchedulerService().getIssues(issueId)

它返回错误:SyntaxError: await is only valid in async function

我从node.js开始。我该怎么解决?


我已经尝试过

  • 在第1行的初始功能const SchedulerService = await function(){之前添加异步

  • 在第一个返回return async () => {上添加异步,其中第3行的return {


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

非常感谢您!

1 个答案:

答案 0 :(得分:0)

如果您用getIssues和{em>和{em} issueId来解决issueRecords,则可以在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));
}