【发布时间】:2016-12-08 13:17:35
【问题描述】:
不熟悉异步和苦苦挣扎。作为下面的示例,我希望初始化一个表,然后通过以下方式处理它的内容: a) 删除旧数据 b) 插入新记录 c) 将表读入数组 d) 显示数组
'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 等异步环境中进行编码。
【问题讨论】:
标签: node.js asynchronous pg-promise