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);
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);
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.
Code to create a promise chain is executed synchronously. The following statement
Promise.resolve(1).then(isGuest && getGuestUserID).catch(err);
is executed as follows:
Promise.resolve(1), which returns a promise fulfilled with the number 1,isGuest && getGuestUserID is evaluated, which in JavaScript results in the value getGuestUserID, a function object.then method of the promise created in step 1 is called with getGuestUserID as argument.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.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.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).