0

I have a conditional if statement who's logic needs to be wrapped in a promise as the logic after if can only be executed after it.

// WRAP 'if' statement below IN A PROMISE
if (a) { // could be true or false. If false, resolve the promise
    // logic here
}

.then(
    // execute logic after if here
)

I'm new to nodejs and am trying to wrap my head around this. How can I solve this ?

tsaebeht
  • 1,570
  • 5
  • 18
  • 32
  • Please, can you restructure your question for easy understanding? – Cocest Jan 01 '19 at 13:18
  • 1
    If you don't have any asynchronous processing, you don't need promises. Any statements you want to execute *after* other statements (like an `if` block) should just follow after those statements in the same block. If you *do* have some asynchronous API call, then please show this in your code. – trincot Jan 01 '19 at 13:25

2 Answers2

1

Just wrap it into a new Promise:

new Promise((resolve, reject) => {
   if(a){
      reject("error");
   } else {
     resolve(yourData);
   }       
})
.then(data => {
 // Do stuff
})
.catch(err => {
  // You should catch here an error rejected above
})
Slawomir Wozniak
  • 489
  • 6
  • 14
0

The question is unclear a bit. Here is answer according to what I understand. You can not run code inside promise once it is resolved or rejected.

new Promise((res, rej) => {

    if (false) {


    }
    res();
    console.log('More code') // this will not run

}).then(() => {

    console.log('This will run')

})
Nafees Anwar
  • 6,324
  • 2
  • 23
  • 42