使用具有回调函数的forEach和asyncawait

时间:2018-02-28 03:33:40

标签: node.js async-await

我尝试在带回调的cronjob上使用asyncawait,此回调是来自API的数据:

这是代码的一部分:

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

我获得api的功能是:

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

你能帮忙吗,我无法修复,我尝试使用返回而不是回调,但仍然无法工作......

谢谢!

更新

我更改了我的代码,感谢@jfriend00 ...

使用“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
};

和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'
})

1 个答案:

答案 0 :(得分:1)

await arr.forEach()无效,正如您所期望的那样。在您的情况下,您希望使用map()来制作它,以便等待一系列承诺。

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

我写了一篇关于让forEach()使用async / await工作的详细博文,如果你想了解更多信息,请查看它:http://thecodebarbarian.com/basic-functional-programming-with-async-await#motivation-and-foreach-