0

I am using NodeJs, Express and async libarary. I am trying to fetch data from elasticsearch and return that information to the user. Here is my code:

1. // function that generates the ES query I want
const generateEsQuery = (source,target)=> (callback)=>{
    let query = {} // some query that I generated
    callback(null,callback)
}

2. // functions that I want to call after the fetching the query
const readElasticData =(data)=> async(callback) =>{

    const trafficData =await elasticClient.search({"ignoreUnavailable":true,index:data.indexes,body:{"query":data.query}},{ignore: [404]});
    callback(null ,trafficData)
}

async function readEsData (data,callback){
    const trafficData =await elasticClient.search({"ignoreUnavailable":true,index:data.indexes,body:{"query":data.query}},{ignore: [404]});
    callback(null ,trafficData)
}

3. // Calling my funtions
function myFunction(information){
    // async.waterfall([generateEsQuery(information[0],information[1]),readElasticData],// The second function doesnt even run
    async.waterfall([generateEsQuery(information[0],information[1]),readEsData] // the second functions runs but doesn't return the results to the callback
    function(err, results) {
            console.log("All Results",results);
            return results;
        });
}

I have two functions one to generate a ElasticQuery (1) and another to execute the query (2), I am trying to use the waterfall function of async library to execute them once after another , but I am unable to fetch the results at the final callback. Out of the two functions that I use to read data , the second one "readEsData" atleast runs after the "generateEsQuery" function. I am new to Node js and I am not sure what I am doing wrong.I also do not want to combine the two functions as I will be reusing the first one in other places.
I am following this approach : https://medium.com/velotio-perspectives/understanding-node-js-async-flows-parallel-serial-waterfall-and-queues-6f9c4badbc17
Question : How do I send the result of the second function through the callback.

Ashok kumar
  • 149
  • 1
  • 10
  • Don't use the async.js libary (callback-based) together with `async`/`await` syntax (promise-based). Just embrace promises. – Bergi Jun 15 '20 at 19:37
  • Please ask only one question per post. Your first one, while slightly off-topic, is answered in detail [here](https://stackoverflow.com/q/38479859/1048572). – Bergi Jun 15 '20 at 19:41
  • *Or find a library that generates Promise-like objects, so it can interoperate. Note that there are some optimizations in V8 that allow async/await to outperform handwritten Promisified code. – user120242 Jun 15 '20 at 20:13

0 Answers0