0

Trying to access the object outside of the function, I know it has to do with the async code. I want to pass the pool.then.res to another module to process into a table.

I'm using this and getting no result:

function createAL2(){
    return new Promise(function(res, rej){
            pool
                .connect()
                .then(client => {
                    return client
                        .query(select)
                        .then(res => {
                            res //console.log(res) will return the JSON object, this is what I want to get my hands on
                            client.release()
                        })
                        .catch(err => {
                            client.release()
                            console.log(err.stack)
                    })
                })
            
    });
};    


createAL2()
    .then(function(x){
        console.log(x);
    })
    .catch(function(){
        console.log(err)
    });

Ideally, I want to return the JSON object outside the function. I'm new to this, have read this answer How do I return the response from an asynchronous call? and tried to apply but cannot get any success, what am I doing wrong?

Thanks!

simplesam
  • 61
  • 7

1 Answers1

3

You create and return a new promise but you dont resolve it in that context, also your resolve function is named res and you overwrite it in the scope of .query.then(res => so you cant use your resolve function res there.

Try it like this

function createAL2(){
    return new Promise(function(resolve, reject){
        pool
            .connect()
            .then(client => {
                return client
                    .query(select)
                    .then(res => {
                        client.release()
                        // resolve your promise with your data here
                        resolve(res); //console.log(res) will 
                        // return the JSON object, this is what 
                        // I want to get my hands on
                    })
                    .catch(err => {
                        client.release()
                        console.log(err.stack)
                        // after you caught your exception 
                        // here reject your promise so you can
                        // catch it at the function call again
                        reject(err);
                    })
            })

    });
};


createAL2()
    .then(function(x){
        console.log(x);
    })
    .catch(function(err){
        console.log(err)
    });
BraveButter
  • 1,408
  • 9
  • 22