異步和掙扎的新手。正如下面我想初始化一個表的實例隨後處理它通過的內容: a)拆下舊數據 b)中插入一個新的記錄 c)讀取該表到一個數組 d)顯示陣列異步db編程的排序動作
'use strict';
// ================================================================================
// Module dependencies
var pgp = require('pg-promise')();
// ================================================================================
//Configure the database connection
var config = {
user: 'user', //env var: PGUSER
database: 'database', //env var: PGDATABASE
password: 'password', //env var: PGPASSWORD
};
var db = pgp(config);
// ================================================================================
// Initialise rhe variables
var customers = [];
// ================================================================================
// Initialise table
db.none("DELETE FROM testing")
.then(function(data) {
console.log("Deleted old records");
// success;
})
.catch(function(error) {
console.log(error);
});
db.none("INSERT INTO testing (firstname, surname) VALUES ('Bob', 'Brown')")
.then(function(data) {
console.log("Inserted new record");
// success;
})
.catch(function(error) {
console.log(error);
});
// ================================================================================
// Display records
db.any("SELECT * FROM testing")
.then(function(data) {
console.log("Looping records");
data.forEach(function(row, index, data) {
customers.push(row.firstname, row.lastname);
console.log(row);
});
})
.catch(function(error) {
console.log(error);
});
console.log("The customers are:");
console.log(customers);
輸出結果不符合要求,但與預期相符。有趣的是,在「插入新記錄」之後,在命令提示符被重新調用之前等待了30秒。
The customers are:
[]
Looping records
anonymous {
id: 3,
firstname: 'Bob',
surname: 'Brown',
created: 2016-08-03T01:43:34.880Z }
Deleted old records
Inserted new record
我的問題是最終與異步編程肯定有地方行動需要在序列,如上面的例子,在這種情況下怎麼能這樣在異步環境中編碼如Node.js的執行情形。
非常好,謝謝你這麼多。我可以問:(a)在db語句允許它連接到下一個「.then」之前「返回」,而不是嵌套,這是我最初的期望? (b)爲什麼「db.none」會影響排序,我沒有得到那點意見。 (c)如果我想要插入兩條記錄而不是一條記錄,可以修改示例來顯示它。再次感謝。 – Dercni
進一步思考。如果「.then」部分是異步操作完成後執行的部分,那麼這不是「回調」所做的。或者承諾回調的演變意味着不再需要使用回調。 – Dercni
你也應該使用'task'或'tx'來針對相同的連接執行它。我會在幾個小時內發佈我的詳細答案,當我得到片刻。同時,請查看[Chaining Queries](https://github.com/vitaly-t/pg-promise/wiki/chaining-queries)。 –