I have a question regarding promises in nodeJS when using Rethindb. This code will give me the results from db first time anything changes, not more.
Lets say I start the script and add a row to the db, the new data will be printed in cmd. But if I add another one, nothing are shown. Something wrong with the way I use the promise? (and no, I dont want to use callback)
Thx!
PushData(r, table)
.then(res=>{
console.log(res);
}
function PushData(r, table){
return new Promise(function(resolve, reject){
r.table(table)
.changes()
.run()
.then(function(cursor){
cursor.on("error", function(err) {
reject(err)
})
cursor.on("data", function(data) {
resolve(data);
})
});
});
}
A promise is only resolving to one value, and calling
resolve()
multiple times on a promise only return that value each time. That's not what you want.What you want to do instead is to repeatedly call
cursor.next()
to get more values, one promise after another.However, you may be also interested by another similar feature of ES6: the Asynchronous Iterator.
Here is my code for converting the cursor from rethinkdb into an async iterator: