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:
- The JavaScript engine calls
Promise.resolve(1)
, which returns a promise fulfilled with the number1
, - The argument expression
isGuest && getGuestUserID
is evaluated, which in JavaScript results in the valuegetGuestUserID
, a function object. - The
then
method of the promise created in step 1 is called withgetGuestUserID
as argument. - Because the promise is already fulfilled,
then
method code puts a job in the Promise Job Queue to callthen
's first argument (getGuestUserID
) with the fulfilled value of the promise,1
, as argument. - The
catch
method of the promise returned from thethen
call in step 3 is called with argumenterr
, a function. This call returns a promise which is not used. - 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.
- Any jobs in the Promise Job Queue are executed on a FIFO basis, which includes the job put there in step 4.
- Promise job execution calls
getGuestUserID
with argument1
, 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).