简体   繁体   中英

Observables and Sequelize promises

Good morning,

I'm having an issue understanding how Sequelize and RxJS work together. From what I read, Sequelize uses promises. Now, what happens if I want to load a list and render everytime an element is found in my database ? I'm using this syntax from sequelize:

User.findAll().then()

But what i want is to have this wrapped in an observable and be able to use :

var getAllUsersObservable = Rx.Observable.create(function (obs) {
  obs.next(user)
}

Then my observer just want, let's say, to print the new user.

var getAllUsersObserver = {
  next: console.log(user)
}

To me, this will not work because Sequelize will only put the list of all my users in its promise when it's done finding all users. My question is : how do I use these two together to have my users being printed, one at a time?

Thanks in advance

I haven't tried this yet, but I do have the same question and will investigate it later. But it does look like you can create an Observable object from a promise. See this: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/promises.md

I would imagine doing something like this would be the best way to blend Observables and promises together.

 let observable1 = Rx.Observable.fromPromise(User.findAll()); observable1.subscribe(...); 

You might have to do some other RX operations, such as Map, SwitchMap, etc., but it looks like this might get you closer to what you're after.

Hope this helps!

Thank you very much ! As I am new to stackoverflow, I forgot to come back to explain how I solved my issue. I'll learn to do that more.

As it turned out, Rx.Observable.fromPromise really did the trick. However, we chose another solution, which is the use of

Rx.Observable.create(obs => { User.findOrCreate(......).spread((user, 
created) => obs.onNext({whatever}) )}

And it's working great for now. Hope that also helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM