Profer
Profer

Reputation: 643

How to return error from asynchronous call

I have a function written in a file.

async myfunction() {
  try {
    const data = await achievementService.stepsPerDayAchievement()
    console.log(data)
  } catch(err) {
    console.log(err)
  }
}

I call another function from here which is written in another file called achievement.

  async stepsPerDayAchievement(user, stepsCount) {
    try {
      await ApiCall()
    } catch (err) {
      return err
    }
  }

But when I return err from this function it suppose it as function return and I get the error in data. What I need here is when I throw error from the stepsPerDayAchievement function it goes to the error part in my first file of function

Can someone please help what I am doing wrong here

Upvotes: 0

Views: 348

Answers (2)

Hussain Ali Akbar
Hussain Ali Akbar

Reputation: 1655

You need to throw an error from the stepsPerDayAchievement method:

  async stepsPerDayAchievement(user, stepsCount) {
    try {
      await ApiCall()
    } catch (err) {
      throw new Error(err);
    }
  }

this way it will land in the catch block of the calling function.

Upvotes: 4

mstfyldz
mstfyldz

Reputation: 482

Since async functions return promises you don't need try catch block in stepsPerDayAchievement function. I think your code should be like below:

async myfunction() {
    const data = await achievementService.stepsPerDayAchievement()
    .then(()=> console.log(data);)
    .catch(()=> console.err("error");)
}

 async stepsPerDayAchievement(user, stepsCount) {
      var apiCallResultData = await ApiCall();
      return apiCallResultData
  }

Upvotes: 3

Related Questions