【发布时间】:2020-06-08 12:41:40
【问题描述】:
我尝试使用 axios 读取 HTTP 响应,并使用 stream-json 以流模式解析 JSON,这样我就可以按需完全适应我的数据库。它运行良好,但如果我尝试关闭数据库连接,一切都会崩溃,因为连接将很快关闭。 问题是:await 不会等待 extract_coins 函数完成(即使它正在返回承诺)并在最终范围内关闭数据库连接。
const main = async() => {
const dbcfg = config.get('db.coins');
const db = await coins_db_configure(dbcfg);
try {
console.log('Connected to the database and created coins table!');
await extract_coins('some_url_which_gives_correct_json', coins_emitter);
}
catch(e){
console.error(e);
}
finally {
await db.close();
}
};
main();
extract_coins:
module.exports = async function extract_coins(url, emitter){
return await axios({
method: 'get',
url: url,
responseType: 'stream'
}).then((res) => {
const pipeline = chain([
res.data,
parser(),
pick({filter: 'data'}),
streamArray()
]);
pipeline.on('data', data => {
emitter.emit('coin_extracted', data.value);
});
pipeline.on('end', () => console.log("All the coins were successfully passed!"));
});
};
【问题讨论】:
-
您没有在提取函数中返回任何内容。
-
您的管道发生了异步事情,这不是基于承诺的,因此不会等待。
-
@Phix 我返回 Promise 并希望 await 了解“结束” - 事件应该实现承诺
-
@trincot,就像你说的,我删除了我所有的 cmets。
标签: javascript json asynchronous async-await axios