0

Before read: Sorry for my english level.

var match = matchPromise != undefined ? matchPromise.then(ret_val =>
    {
        return ret_val;
    })
    : false;

    if (match) {
        //continue here after Promise response
    }

My question is, how to wait before enter in the if ? because everytimes match == false, but match can be true if hes answered by the promise.

I hope you understand my problem.

Thanks.

tk3
  • 990
  • 1
  • 13
  • 18
Acate
  • 1
  • 3
  • I think what you need is `Promise.all([...promises])`. If you call `Promise.all([match]).then((val) => ...)` then place your if inside the then callback, it will resolve match in every case (if promise, it waits for promise and resolves, if value, it resolves immediately) – Fabio Lolli May 16 '18 at 10:40
  • @Quentin I don't think it's a duplicate of THAT specific question... Poorly asked, but I think his problem was "How do I handle a value that could be a promise or a value?" – Fabio Lolli May 16 '18 at 10:42
  • `(matchPromise || Promise.reject("not defined")).then(...).catch(...)` – Jonas Wilms May 16 '18 at 10:52
  • @quentin i agree to fabio. This isnt really an exact dupe ... – Jonas Wilms May 16 '18 at 10:53
  • I've updated my answer with some more explanation. Quentin must have duped it because your code tries to get the resolve value of a promise in a synchronous way, this is not possible. You can however turn your possibly non promise value into a promise with `Promise.all` and `Promise.reject` as suggested in comments or `Promise.resolve` as in my answer. – HMR May 16 '18 at 11:34

2 Answers2

0

You're looking for

(matchPromise != null
  ? matchPromise
  : Promise.resolve(false)
).then(match => {
    // continue here after Promise response
});

Notice that you cannot wait for anything without making your code asychronous.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
-2

You can wrap a possible promise in Promise.resolve and use .then on it

Promise.resolve(matchPromise).then(
  match=>{
    if(match){...
  }
)

To clarify: you cannot read a promise in a synchronous way, your only options for a promise is to use .then or async/await. There is a way to turn a synchronous value (in your case undefined) to a promise with Promise.resolve (in your case a promise of undefined).

So now it doesn't matter anymore if matchPromise is a promise or not because you make sure it is and then process it in .then that will either give you the resolved value or the undefined value, either way; the result of the if statement is the same.

HMR
  • 37,593
  • 24
  • 91
  • 160
  • 1
    @Quentin I thought `matchPromise` was either undefined or a promise so you can't do `.then` on undefined but can't assume the resolve of `matchPromise` is undefined/falsy when it is a promise. Therefor wrap it in `Promise.resolve(undefined or something resolving to possibly false).then(result=>didn't matter if it was undefined result would just be undefined)` – HMR May 16 '18 at 10:45