如何发现 id,并等待现有的 Promise? [英] How to discover the id, and await an existing Promise?
问题描述
最简单的解决方案可能是一些添加一些之后等待
承诺模式,或重用...() 或方法 parse()
,如下所示.
The simplest solution is perhaps some await
after adding some promise pattern, or reusing...
I not see how to reuse the Promise, that I suppose it already exists, into the method csv-parse.readFileSync()
, or the method parse()
, illustrated below.
另一个解决方案是添加更多的承诺和一些async/await:整个 LOAD 块可以是一个函数......但我也没有看到等待的地方.
Another solution is to add more promises and some async/await: the whole LOAD block can be a function... But I also not see where put the awaits.
'use strict';
const fs = require('fs')
const path = require('path')
// CONFIGS:
const cf_cover_dataset = '../data/cover.csv'
var COVER = null;
// LOAD external configs:
var COVER_file = path.resolve(__dirname, cf_cover_dataset);
if (path.extname(cf_cover_dataset)=='.csv') {
const parse = require('csv-parse') // npm i csv-parse (not parse"r")
let raw = []
parse(fs.readFileSync( COVER_file ), {
trim: true,
skip_empty_lines: true
})
.on('readable', function(){
let record
while (record = this.read()){
raw.push(record) ; console.log('.')}
})
.on('error', function(err){ console.error(err.message) })
.on('end', function(){
// I NEED TO WAY THE END HERE, HOW TO?
COVER = f(raw);
console.log("1. cover from CSV");
});
} else {
COVER = JSON.parse(COVER_file) // ... and WAY here
console.log("1. cover from JSON");
}
console.log("2. END!!");
结果是
2. END!!
1. cover from JSON
如何在step1之后得到step2?
How to get step2 after step1?
推荐答案
这更多是一种解决方法,而不是真正的解决方案,例如使用等待
.
(请编辑这个答案,它是一个维基,你可以纠正我的假设,我的英语,或添加线索和链接)
This is more one workaround, not a real solution using e.g. await
.
(please edit this answer, it is a Wiki, you can correct my asumptions, my English, or add clues and links)
似乎唯一的解决方案是丑陋天真的解决方案,将所有软件封装在一个main()
函数中:
Seems that the only solution is the ugly naive solution, encapsulating all software in a main()
function:
if (path.extname(cf_cover_dataset)=='.csv') {
...
parse(fs.readFileSync( COVER_file ), {
...
})
.on('readable', function(){
...
})
.on('error', function(err){ ... })
.on('end', function(){
COVER = f(raw);
console.log("1. cover from CSV");
main();
});
} else {
COVER = JSON.parse(COVER_file) // ... and WAY here
console.log("1. cover from JSON");
main();
}
function main() { // step2, ugly but run in sequence
console.log("2. END!!");
}
<小时>
我真正需要的是承诺的非文档名称,以便于等待所有人.查看问题
What I really need is the non-documented name of the promises to be easy to await all. See the problem
这篇关于如何发现 id,并等待现有的 Promise?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!