0

I'm trying my best to understand nodeJS/typescript and it techniques. But still can't figure out how I can save my databasequery result into a variable and return it. Maybe someone can explain me the problem / help me:

I have a method like this:

public getAllProducts(): ProductArray {
    // returns IConnection from "mysql" and connect
    this.databaseConnection.getConnection().connect();

    var product: any = [];
    this.databaseConnection.getConnection().query('SELECT * FROM product', function (error: any, results:any, fields:any) {
        if (error) throw error;
        product.push(results);
    });



    console.log(product);
    return product;
}

Would be nice if someone can help me out here.

1
  • 1
    return product should inside call back function which is function (error: any, results:any, fields:any) { if (error) throw error; product.push(results);} Commented Jun 13, 2017 at 18:48

1 Answer 1

3

You are not supposed to be able to return a variable from an async function. You should go ahead and read some articles about how to combat callback hell. All your logic that requires this data should be inside the callback function of the query. Some options to make your code look a little bit better is using the async.js module or promises (you can also check the async/await that was added on nodeSJ 7.6.0 version.

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

3 Comments

Promises is the way to go here, unless you're prepared to use the new async features in the latest Node.
ok, thanks for the answer! So as soons as I want to query somethings I need to do everything inside of the function? From the request till the response?
Thats how the callback hell term was brought to life. Go ahead and check how promises work to prevent that.

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.