节点流未完成但发出结束

node stream not finish but emit end

我正在阅读 this 并根据示例编写我的代码。

我的代码:

const through = require('through2'); const bluebird = require('bluebird');

function streamToPromise(stream) {
  return new Promise(function(resolve, reject) {
    stream.resume();
    stream.on("end", resolve);
    stream.on("error", reject);
  });
};

module.exports = {
  up: function up() {
    console.log('startstream');
    // Doc is sequelize Model
    const stream = Doc.createReadStream({
      include: [
        {
          repository: AssociatedRepo,
          as: 'on',
          required: false,
        },
      ],
    });

    stream.pipe(through({ objectMode: true }, (doc, enc, cb) => {
      console.log('docid', doc.id);
      return doc.destroy()
        .then(() => cb());
    }));
    return streamToPromise(stream).then((data) => {
      console.log('xxxxxxxxxx', data);
      return null;
    });
  },
};

我尝试用上面的程序读取和删除了大约400条记录。但是从日志中,我发现流 promise (streamToPromise(stream)) 正在解决,但仍然有几条记录。从日志中,我得到:

xxxxxxxxxx undefined
docid 89934915596

如何解决这个问题?谢谢

您需要等待 pipe 的目标流结束,目前您只在等待输入流。使用

const res = stream.pipe(through({objectMode: true}, …));
return streamToPromise(res);