[英]How to access a variable from a knex query inside of a second knex query?
我有以下路線,我想要從第一個查詢獲得的ID的總和
app.post('/VerEmpresas', function (req, res) {
var r, dot, ide;
knex.from('empresas').select("id", "rut", "empresa", "razon_social", "email")
.then((rows) => {
for (row of rows) {
ide = row['id'];
knex.from('sucursales').sum("dotacion as SUM").where('id_empresas', '=', ide)
.then((q0) => {
dot = q0[0].SUM;
console.log(dot);
})
console.log(dot);
// do something here with dot
}
res.send();
})
})
第一個console.log顯示正確的值,但是第二個console.log顯示未定義。 我如何在then()
之外使用變量?
當您使用then
,您正在處理異步代碼,這意味着程序遵循的路徑不是線性的。 您可以在此處閱讀有關如何從異步調用返回值的更多信息。
在您的情況下,第二個console.log在定義點之前運行。 這聽起來可能很奇怪,但是在第二個console.log運行時,數據庫調用只是沒有完成。 為了使用定義之后的點值,就得鏈中的另一個then
在同一鏈。 像這樣:
app.post('/VerEmpresas', function (req, res) {
var r, dot, ide;
knex.from('empresas').select("id", "rut", "empresa", "razon_social", "email")
.then((rows) => {
for (row of rows) {
ide = row['id'];
knex.from('sucursales').sum("dotacion as SUM").where('id_empresas', '=', ide)
.then((q0) => {
dot = q0[0].SUM;
console.log(dot);
})
.then(() => {
console.log(dot);
// do something here with dot
})
}
res.send();
})
})
然后第二個在第一個then
運行。 通常情況下,你傳遞的結果之間then
,返回和參數秒,但在你的情況,你有這使得它獲得這樣的函數的頂部聲明使用var點。
您的代碼還有另外兩個問題,但這超出了此問題的范圍:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.