How to discover the id, and await an existing Promise?

你。 提交于 2019-12-14 03:10:23

问题


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.

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!!");

The result is

   2. END!!
   1. cover from JSON

How to get step2 after step1?


回答1:


csv-parse offers a sync API according to https://csv.js.org/parse/api/#sync-api

I guess using this works around the whole promise/callback hassle you want to avoid




回答2:


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)


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




回答3:


you are reading file in sync mode but you are parsing in async mode. To use the parser in sync mode, like previously explained, you must require csv-parse/lib/sync to use the CSV parse sync API.

See my answer onGitHub which include an example.



来源:https://stackoverflow.com/questions/54170238/how-to-discover-the-id-and-await-an-existing-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!