1

I have below function

const initSync = () => {
  return localDB
    .sync(remoteDB, {
      live: true,
      retry: true
    })
    .on('change', function(change) {
      if (change.direction === 'pull') {
        console.log(change.change.docs) //this worked
        return change.change.docs
      }
    })
}

I want to call it somewhere

I do const result = await initSync(), but in result I get nothing, I feel strange, should I wrap it with a promise for above function?

Hanz
  • 499
  • 7
  • 18
  • 1
    Not knowing anything about your framework, but `.on()` sounds like an add Event Listener method, that's quite rare these return Promises. – Kaiido Apr 08 '19 at 04:32
  • there's never any point in returning a value from a `on` handler, since it gets discarded, since there's nothing to return a value **to** (because, as noted above, it's an event listener) ... knowing this, you should be able to figure out your mistake – Jaromanda X Apr 08 '19 at 04:32
  • short answer, in the above case it actually does make sense to wrap the code in a `new Promise` - however, I'd still be looking at a different solution, personally - by the way, there's no evidence of any Promise at all in that code – Jaromanda X Apr 08 '19 at 04:34
  • @JaromandaX https://pouchdb.com/api.html#sync, how can I not connecting to the db and use `on` in multiple places? – Hanz Apr 08 '19 at 04:40
  • @Kaiido so what should I do? chain the .on at somewhere else? like `initSync.on('change' => {})` ?? – Hanz Apr 08 '19 at 04:41
  • as I said, wrap it in a Promise ... seeing as there's not Promise already anyway, it's not like you'll have that Promise with a Promise you're worried about ... https://jsfiddle.net/9rjboxgf/ – Jaromanda X Apr 08 '19 at 04:43
  • It's generally a bad idea to wrap event based systems in Promises, but if you're sure that the next event will indeed be for you, then `const initSync = () => new Promise(resolve => localDB .sync([...].direction === 'pull') { resolve (change.change.docs) })` – Kaiido Apr 08 '19 at 05:09

0 Answers0