0

im try to use asyncawait on a cronjob with callback, this callback are data from an API:

This is part of the code:

var sending_email = new CronJob({
    cronTime: time_hour,
    onTick: function(){
        console.log('Funciona cada: ', time_hour);

        sendService.GetSenderList(function(datos){
            console.log('a enviar: ', datos);
            var arrayInfo = [];

            await (
                datos.forEach(function(hash){
                //console.log('a enviar: ', hash.HASH_TOKEN);

                    var wait = sendService.GetMailContent(hash.HASH_TOKEN, function(content){
                        arrayInfo.push(content);
                        console.log(hash.HASH_TOKEN,content);
                    });
                })
            );

            console.log('array: ',arrayInfo);
        })
    },
    start: false,
    timeZone: 'Chile/Continental'
})

And my function to get api are:

exports.GetSenderList = async (function(callback){
    await (client.get(constant.API_URL_SENDER, function (data, response) {
        callback(data);
    }));    
});

exports.GetMailContent = async.iterable (function(hash,callback){
    await (client.get(constant.API_URL_CONF+'/'+hash, function(data, response) {
        callback(data)
    }))
})

Could you helpme, i can't fixed, i try with return instead of callback, but still doen't work...

Thanks!

UPDATE

i change my code, thanks @jfriend00...

using "node-rest-client-promise"

var constant = require('./constant.json')
var mailConfig = require('./mailConfig.json')
// var forEach = require('async-foreach').forEach;
//var async = require('asyncawait/async');
//var await = require('asyncawait/await');

var nodemailer = require('nodemailer');

//var Client = require('node-rest-client').Client;
//var client = new Client();

var nodeRestClient = require('node-rest-client-promise');
var client = nodeRestClient.Client({
    requestConfig: {
        timeout: 30000, //request timeout in milliseconds 
        noDelay: true, //Enable/disable the Nagle algorithm 
        keepAlive: true, //Enable/disable keep-alive functionalityidle socket. 
        keepAliveDelay: 100000 //and optionally set the initial delay before the first keepalive probe is sent 
    },
    responseConfig: {
        timeout: 50000 //response timeout 
    }
});


exports.GetSenderList = function() {
    let lista = client.getPromise(constant.API_URL_SENDER);
    //console.log('Get lista: ',lista)
    return lista
};

exports.GetMailContent = function(hash) {
    var normalHash = hash.replace(new RegExp("/", 'g'),"%2F");
    //console.log(normalHash);
    let lista = client.getPromise(constant.API_URL_CONF + '/' + normalHash);
    return lista
};

and on cron:

var sending_email = new CronJob({
    cronTime: time_hour,
    onTick: async function(){
        console.log('Funciona cada: ', time_hour);

        let arrayInfo = [];
        let arrayHash = [];
        let datos;

        try{
            datos = await sendService.GetSenderList();

            //console.log('datos: ', datos.data);

            for(let hash of datos.data){
              //console.log('hash', hash);
              let content = await sendService.GetMailContent(hash.HASH_TOKEN)
              arrayHash.push(hash.HASH_TOKEN);
              arrayInfo.push(content.data);
            }

            console.log('array: ', arrayInfo);
        }
        catch(e){
            console.log("onTick error ", e);
        }
    },
    start: false,
    timeZone: 'Chile/Continental'
})
4
  • what is the error or what is the output your getting? Commented Feb 28, 2018 at 3:48
  • Is not a error, just return with different times, so i cant match the hash i send with the answer! Commented Feb 28, 2018 at 14:01
  • We have to see the code inside of client.get(). It appears to be an odd function because it is asynchronous, but has no way of communicating back an error. There is likely a design problem with that function unless there is no possible error from it. Commented Feb 28, 2018 at 21:34
  • I temporarily deleted my answer because I realized that util.promisify() will not work with client.get() because it does not follow the classic node.js callback interface for asynchronous operations (the callback should be (error, result), but yours is (data, response) which won't work with util.promisify(). That's why it was always giving you an error. I can fix my answer if you show us the code for client.get() so we can properly promisify it. Commented Feb 28, 2018 at 21:36

1 Answer 1

1

await arr.forEach() doesn't work as you'd expect. In your case, you want to use map() to make it so you're awaiting on an array of promises.

await (Promise.all(datos.map(hash => sendService.GetMailContent(hash.HASH_TOKEN))));

I wrote a detailed blog post about making forEach() work with async/await, check it out if you want to learn more: http://thecodebarbarian.com/basic-functional-programming-with-async-await#motivation-and-foreach-

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.