Home > OS >  Why console for isGuest is not printed. I'm getting output as The Id is 1
Why console for isGuest is not printed. I'm getting output as The Id is 1

Time:09-11

function getGuestUserID(v)
{console.log('The Id is',v)};

function isGuest(val){ console.log('hl') 
return false};

function err(e) { console.log("error", e); }

Promise.resolve(1).then(isGuest && getGuestUserID).catch(err);

CodePudding user response:

You never call the isGuest function, and it's not used as an argument that is passed to the .then() method. The arguments of a funnction are evaluated first before the .then() method is called, so your code is the analogous to:

const thenFn = isGuest && getGuestUserID;
Promise.resolve(1).then(thenFn).catch(err);

Because isGuest is a function object, it is cosidered truthy, so thenFn gets assigned to the getGuestUserID function. Notice here how you're not calling the isGuest() method in this case.

You can instead create a callback function that handles this for your when your Promise resolves:

Promise.resolve(1).then((v) => isGuest(v) && getGuestUserID(v)).catch(err);

or you can use an if-statement to mak it a bit more readable:

Promise.resolve(1).then((v) => {
  if(isGuest(v))
     return getGuestUserID(v);
}).catch(err);

The above two examples are slightly different in what they return. So depending on your use case you may want to keep that in mind.

CodePudding user response:

Code to create a promise chain is executed synchronously. The following statement

 Promise.resolve(1).then(isGuest && getGuestUserID).catch(err);

is executed as follows:

  1. The JavaScript engine calls Promise.resolve(1), which returns a promise fulfilled with the number 1,
  2. The argument expression isGuest && getGuestUserID is evaluated, which in JavaScript results in the value getGuestUserID, a function object.
  3. The then method of the promise created in step 1 is called with getGuestUserID as argument.
  4. Because the promise is already fulfilled, then method code puts a job in the Promise Job Queue to call then's first argument (getGuestUserID) with the fulfilled value of the promise, 1, as argument.
  5. The catch method of the promise returned from the then call in step 3 is called with argument err, a function. This call returns a promise which is not used.
  6. Execution continues after the Promise chain statement, possibly executing synchronous code that follows it, before returning control to task management components of the event loop.
  7. Any jobs in the Promise Job Queue are executed on a FIFO basis, which includes the job put there in step 4.
  8. Promise job execution calls getGuestUserID with argument 1, which prints "The id is 1" on the console.

If you call then on a pending promise, the part about putting a job in the Promise Job Queue described in step 4 doesn't happen when then is called and is delayed until when (and if) the promise is actually fulfilled or rejected (and hence no longer pending).

  • Related