0

I have a very simple two methods in Vuejs and it returns me promise pending what I am doing it's this:

TotalIncomeData(day, branch_office_id) {
            return fetch('/api/collection/total/'+day+'/'+branch_office_id+'?api_token='+App.apiToken)
            .then(response => {
                    return response.data;
                }
    );
 },
 getTotalIncomes(day, branch_office_id) {
     console.log(this.TotalIncomeData(day, branch_office_id))
 },

Why am I not getting the value? Thanks

Medicina NA
  • 55
  • 1
  • 6
  • 2
    `TotalIncomeData` returns `fetch(...).then(...)`, which is a Promise. You should call its `then` function and put `console.log` there. – juzraai Apr 24 '22 at 15:41
  • how can I remove it? – Medicina NA Apr 24 '22 at 15:42
  • You're not getting the value because you don't await it or pass a callback to the then method to receive it. – jonrsharpe Apr 24 '22 at 15:42
  • @jonrsharpe I did this conseole.log(await this.TotalIncomeData(day, branch_office_id)) it displays an error – Medicina NA Apr 24 '22 at 15:43
  • Is the error that you can't await in a non-async method? Because you can't await in a non-async method. – jonrsharpe Apr 24 '22 at 15:44
  • I suggest you read about what Promises are and how to use them properly, then you'll understand why your code doesn't work :) [Guide from MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) – Kapcash Apr 24 '22 at 15:50
  • Possible duplicate of https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – Estus Flask Apr 24 '22 at 16:09

1 Answers1

0

You need to call .json() on the fetch response, and await the result.

And you need to make your function async and await the promise from the first function.

TotalIncomeData(day, branch_office_id) {
  return fetch(...).then(rawResponse => rawResponse.json())
                                                    ^^^^^^ 
 },
 async getTotalIncomes(day, branch_office_id) {
 ^^^^^
     console.log(await this.TotalIncomeData(day, branch_office_id))
                 ^^^^^
 },
tauzN
  • 5,162
  • 2
  • 16
  • 21