1

I am trying to perform a mysql query asyncronously assigning a value to a const to be later used in my code.

What I have so far is:

const plan_free = await con1.promise().query("SELECT stripe_price1 FROM funzioni WHERE titolo='SmartBanca'")
.then( ([rows,fields]) => {
    return rows[0]['stripe_price1'];
})
.catch(console.log)
.then( () => con1.end());
console.log("Plan_free: "+ plan_free);

but plan_free returns [object Object]. I am sure I am close to the goal but I don't get what I am still doing wrong.

Edit: by adding the following lines:

plan_free1 = JSON.stringify(plan_free);
console.log("Plan_free: "+ plan_free1);

I see the following content for plan_free:

Plan_free: {"_events":{},"_eventsCount":0,"next":null}

that actually is not even close to what I want to achieve.

Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74
  • Isn't this the case, because the function is async and thus the line where you do the console.log is getting called before your async task might be finnished? – Olli Jan 04 '21 at 15:25
  • Sure, your console log must be in the resolved then section : just the line following the line where plan_free is declared. – tsamaya Jan 04 '21 at 15:26
  • I need to have the result after the call, not in the callback, in the callback it is correctly evaluated. So I need to fix it. See the edit. – Lelio Faieta Jan 04 '21 at 15:47

1 Answers1

0

Ok, I finally made it.

var plain_free='';
await con1.promise().query("SELECT stripe_price1 FROM funzioni WHERE titolo='SmartBanca'")
.then( ([rows,fields]) => {
    plan_free = rows[0]['stripe_price1'];
    return plan_free;
})
.catch(console.log)
.then( () => con1.end());
            
console.log("Plan_free: "+ plan_free);

This way I was able to fetch the value from the database and assign it to a variable in node. This will be later used in my code without the need to nest it in callback of the query.

Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74