Kevin Amiranoff
Kevin Amiranoff

Reputation: 14468

Javascript Promise, returning null from catch?

In a PR I was reviewing recently, I saw this:

const accessToken = await getAccessToken().catch(() => null);

My question is: Is the catch doing anything here? Does it assign null to accessToken? Would it be different without it?

Upvotes: 2

Views: 4990

Answers (3)

Luke Walker
Luke Walker

Reputation: 501

Arrow functions have implicit returns.

In your code snippet, if getAccessToken() is rejected, catch() will be entered, null will be the value which gets returned to accessToken.

In essence acccessToken could equal (depending on the outcome):

(an example access token)

accessToken = asda8sdaewrascsac;

OR

accessToken = null;


Upvotes: 2

TiagoM
TiagoM

Reputation: 3526

Yes if there is an error not catched inside the getAccessToken, the value inside the promise will be null

const accessToken = await getAccessToken().catch(() => null);  //accessToken will be a promise

accessToken .then(function(value) {
  console.log(value);    // expected output: null
});

Upvotes: 0

Teun van der Wijst
Teun van der Wijst

Reputation: 1019

"The catch() method returns a Promise and deals with rejected cases only." Source

So that line simply says that if an error occures while completing the promise, () => null, which is basically return null inside the Promise.

Upvotes: 1

Related Questions