简体   繁体   English

如何等待 createReadStream 完成?

[英]How to wait for createReadStream to finish?

I am confused because I cannot seem to extract a value from an asynchronous operation .我很困惑,因为我似乎无法从异步操作中提取值 Basically I have to parse a csv file and the operation is asynchronous as shown below.基本上我必须解析一个 csv 文件,并且操作是异步的,如下所示。

const csv = require('csv-parser')
const fs = require('fs')
const results = [];
fs.createReadStream('courses.csv')
            .pipe(csv())
            .on('data', (data) => results.push(data))
            .on('end', () => {
                console.log(results);
            });

I am unable to completly extract and isolate the results variable from that stream.我无法从 stream 中完全提取和隔离结果变量。 I have tried doing this by wrapping it with a promise but it shows pending .我试过用 promise 包装它,但它显示为pending Here is what I am doing.这就是我正在做的事情。

const getData = () => {
    const prom = new Promise((res, rej) => {
        fs.createReadStream('courses.csv')
            .pipe(csv())
            .on('data', (data) => results.push(data))
            .on('end', () => {
                res(results);
            });
    })
    return prom;
}

async function GIVEMEMYVALUE() {
    var result = await getData();
    return result;
};

let data = GIVEMEMYVALUE();
console.log(data);

I have read other questions relating to promises but I still don't see what I am doing wrong.我已经阅读了与承诺有关的其他问题,但我仍然没有看到我做错了什么。 I can do whatever I want with the results variable inside the 'end' callback but cannot seem to extract it(for whatever reason I want to extract it.)我可以对“结束”回调中的结果变量做任何我想做的事情,但似乎无法提取它(无论出于何种原因我想提取它。)

  1. Is it wrong to want to extract that value outside the scope of the 'end' callback?想要在“结束”回调的 scope 之外提取该值是错误的吗?
  2. Can everything I possibly want to do with the results be done inside the callback?我可能想要对结果做的所有事情都可以在回调中完成吗?

I have already gone through How do I return the response from an asynchronous call?我已经完成了如何从异步调用返回响应? but don't quite get it as it doesn't mention anything about pending promises.但不太明白,因为它没有提到任何关于未决承诺的内容。

GIVEMEMYVALUE returns also an promise. GIVEMEMYVALUE还返回 promise。 However you could shorten your processes alot:但是,您可以大大缩短您的流程:

const getData = () =>
  new Promise((res, rej) => {
    fs.createReadStream("courses.csv")
      .pipe(csv())
      .on("data", data => results.push(data))
      .on("end", () => {
        res(results);
      });
  });

getData().then(data => {
  console.log(data);
});

async/ await does not make your code work synchronous. async/ await不会使您的代码同步工作。 As soon as you put async infront of your function, your function automatically returns an promise and acts like an promise.只要您将async放在 function 前面,您的 function 就会自动返回 promise 并像 ZC1C425268DE39BDC29E 一样工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM