确保在 transformFunction 中解决承诺

Make sure promise resolved inside transformFunction

我正在学习through2 and sequelize

我的代码:

  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 是续集模型。我想使用流从数据库中逐个读取 Doc 实例,并删除每个 Doc 实例上的评论。 Comment.findOnecom.destroy() 都会 return 承诺。我想为每个 doc 解决承诺,然后调用 cb()。但是我上面的代码无法运行,在 com 被销毁之前,代码已经完成 运行.

如何解决?谢谢

我把上面的代码包裹在mocha测试中,比如

it('should be found by readstream', function _testStream(){
  /* wrap the first piece of codes here*/
});

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

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

在 运行 .destroy().

之前,您可能还需要检查 com 结果是否为 null
  .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)
})