node.js - 确保在 transformFunction 内解决 promise

标签 node.js sequelize.js node-streams through2

我正在学习 through2sequelize

我的代码:

  return Doc.createReadStream({
    where: { /*...*/ },
    include: [
      {
        /*...*/
      },
    ],
  })
  .pipe(through({ objectMode: true }, (doc, enc, cb) => {
    Comment.findOne(null, { where: { onId: doc.id } }).then((com) => { /* sequelize: findOne*/
      com.destroy(); /* sequelize instance destroy: http://docs.sequelizejs.com/manual/tutorial/instances.html#destroying-deleting-persistent-instances */
      cb();
    });
  }))
  .on('finish', () => {
    console.log('FINISHED');
  })
  .on('error', err => console.log('ERR', err));

我试图清楚地表达我的问题。 DocComment 是 Sequelize 模型。我想使用流从数据库中一一读取Doc实例并删除每个Doc实例的评论。 Comment.findOnecom.destroy() 都会返回 promise。我想为每个 doc 解决 promise ,然后调用 cb() 。但是我上面的代码无法运行,在com被销毁之前,代码已经运行完毕。

如何解决?谢谢

我将上面的代码包裹在 mocha test 中,比如
it('should be found by readstream', function _testStream(){
  /* wrap the first piece of codes here*/
});

但在流读完之前,测试存在。

最佳答案

您可以通过返回 promise 并使用另一个 .then 来等待另一个 promise 。

在运行 com 之前,您可能需要检查 null 结果是否也为 .destroy()

  .pipe(through({ objectMode: true }, (doc, enc, cb) => {
    Comment.findOne(null, { where: { onId: doc.id } })
      .then(com => com.destroy())
      .then(()=> cb())
      .catch(cb)
  }))

然后在 mocha 中运行测试时,需要通过在测试函数签名中添加 done 并在完成或错误时调用 done() 来等待异步流。
it('should be found by readstream', function _testStream(done){
  ...
  .on('finish', () => done())
  .on('error', done)
})

关于node.js - 确保在 transformFunction 内解决 promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47585605/

相关文章:

c++ - 可读 Node 流到 native c++ 插件 InputStream

javascript - Gulp 使用 browserSync 观看

node.js - 在 Windows 10 上卸载 Node.js

node.js - 使用 uglify 将 TypeScript 转为 JavaScript

many-to-many - 非 ID 属性的 Sequelize 多对多

node.js - sequelize 查询的可选参数

javascript - 如何使用 JavaScript 在 mongodb 中设置唯一 id

javascript - 列出来自 Azure Blob 存储的 Blob 和 Node.js 中的 Readstream

node.js - 正确的 Sequelize 流程以避免重复行?

node.js - 错误 [ERR_STREAM_PREMATURE_CLOSE] : Premature close in Node Pipeline stream