问题描述
我正在尝试执行一个 MysqL 查询,以异步方式为常量分配一个值,以便稍后在我的代码中使用。
到目前为止我所拥有的是:
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);
但 plan_free 返回 [object Object]。我确信我已经接近目标了,但我不明白我仍然做错了什么。
编辑:通过添加以下几行:
plan_free1 = JSON.stringify(plan_free);
console.log("Plan_free: "+ plan_free1);
我看到 plan_free 的以下内容:
Plan_free:{"_events":{},"_eventsCount":0,"next":null}
这实际上与我想要达到的目标还差得很远。
解决方法
好的,我终于成功了。
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);
通过这种方式,我能够从数据库中获取值并将其分配给 node.js 中的一个变量。稍后将在我的代码中使用它,而无需将其嵌套在查询的回调中。