-1

I cannot get this to work, and starting to think I've misunderstood something fundamental. I've been through many examples, and I cannot see what I'm doing wrong.

Here is my promise:

myPromise = new Promise ( resolve => {
  if (matchNew(id)) resolve();
})

myPromise.then( () => {
  console.log('resolved');
})

matchNew() is a function that simply returns 'true' after completion of save to database. My console confirms this 'true' return happens, but code is not waiting for it, and the promise above never resolves.

Update

This is what I meant regarding the purpose of MatchNew(): It waits for confirmation from MongoDB that the write is successful, then then returns true.

function matchNew(id) {

  /* do some stuff */

  // update database
  MongoPath.Match
    .replaceOne( {'_id': m._id}, thisMatch, {writeConcern: { j: true}})
    .then( (msg) => {
      console.log(msg);
      return true;
     });
  }

I want to ensure my main code is waiting until I get a return values from matchNew before continuing...

halfer
  • 19,824
  • 17
  • 99
  • 186
Kissenger
  • 345
  • 4
  • 15
  • Move `resolve()` into a callback that `matchNew` calls once it is done doing its thing. – Kevin B Dec 07 '18 at 22:23
  • "*matchNew() is a function that simply returns 'true' after completion of save to database.*" - a function cannot `return` asynchronously. What does it actually do? – Bergi Dec 07 '18 at 22:36

1 Answers1

0

matchNew() is a function that simply returns 'true' after completion of save to database.

Thats impossible. It either returns true immeadiately, or it returns a Promise, that resolves to true on completion. Therefore:

 if (matchNew(id))

is th same as:

 if (new Promise())

and that will enter the branch directly as objects are truthy in javascript. Instead you just want to chain promises:

 matchNew(id).then(matches => {
    if(matches) {
      /*...*/
    } else {
      /*...*/
    }
});
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • updated my post to clarify the purpose of matchNew() function. You'll see that I am indeed attempting to 'return 'true' after completion of save to database', but it's obviously not doing what I had hoped... – Kissenger Dec 07 '18 at 23:01
  • @kissenger `return` the promise from `matchNew`. – Jonas Wilms Dec 07 '18 at 23:05
  • I fixed it but i'm not allowed to answer my own question, so i can't share it. Pity. Thanks to pointing me in the right direction though. – Kissenger Dec 08 '18 at 14:57