【发布时间】:2020-03-17 01:55:47
【问题描述】:
正确输入所有数据后如何结束我的异步连接?
即使在循环外声明连接结束,结构也在第一次 INSERT 后完成
代码
require('es6-promise').polyfill();
require('isomorphic-fetch');
let queryAPI = {
"query": `{
squads {
name
cards(includedOnKanban: true, closed: false, archived: false, cancelled: false, swimlaneName:\"Atividades Nao Transacionais\", updatedSince: \"2020-01-01T00:00:00-0300\") {
identifier
title
description
status
priority
assignees {
fullname
email
}
swimlane
workstate
}
}
}`
};
(async () => {
const rawResponse = await fetch('https://www.bluesight.io/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Bluesight-API-Token': 'token-here'
},
body: JSON.stringify(queryAPI)
});
const content = await rawResponse.json();
const { Client } = require('pg');
const client = new Client({
user: 'postgres',
host: '127.0.0.1',
database: 'postgres',
password: 'postgres',
port: 5432
})
client.connect();
const query = `INSERT INTO tb_bluesight
(identifier,title,description,status,priority,date_insert)
VALUES ($1, $2, $3, $4, $5, current_timestamp)`;
var data = Object.keys(content);
var squads = Object.keys(content[data]);
var cards = Object.keys(content[data][squads][0]['cards']);
try{
for(x in cards){
const parameters = [
content[data]["squads"][0]["cards"][x]['identifier'],
content[data]["squads"][0]["cards"][x]['title'],
content[data]["squads"][0]["cards"][x]['description'],
content[data]["squads"][0]["cards"][x]['status'],
content[data]["squads"][0]["cards"][x]['priority']
];
client.query(query, parameters, (err, res) => {
console.log(err, res);
})
}
}catch(e){
console.log("undefined");
}
client.end();
})();
输出
错误:连接终止 在连接处。 (C:\Users\TESTE\Documents\Autoportal\api\node_modules\pg\lib\client.js:254:9) 在 Object.onceWrapper (events.js:417:28) 在 Connection.emit (events.js:323:22)
【问题讨论】:
-
您需要
await client.connect()和const res = await client.query()来处理pg包的异步性。否则client.end()在你完成工作之前被调用。 -
明白了,这似乎是一个愚蠢的错误,我可以显示一个代码 sn-p 解决这个问题吗?我不明白如何在我的代码中复制这个,拜托!
标签: javascript node.js postgresql api