节点流未完成但发出结束

时间:2017-12-05 20:13:04

标签: node.js promise node-streams through2

我正在阅读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条记录。但是从日志中,我发现流承诺(streamToPromise(stream))正在解决但仍有几条记录。从日志中,我得到了:

xxxxxxxxxx undefined
docid 89934915596

如何解决这个问题?感谢

1 个答案:

答案 0 :(得分:0)

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

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