我正在学习 through2 和 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));
我试图清楚地表达我的问题。
Doc
和 Comment
是 Sequelize 模型。我想使用流从数据库中一一读取Doc实例并删除每个Doc实例的评论。 Comment.findOne
和 com.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/