fetch function returns promise instead of object

I have a function named getData in functions.js, when I called in another file, scripts.js it returns promise not an object.

//------ functions.js ------

export async function getData(arg1,arg2,arg3) {

...

let result = await fetch(proxyUrl + targetUrl, requestOptions)
    .then(response => response.json())
    .catch(error => console.log('error', error));

return result
    }

When I call like this I get a Promise:

//------ scripts.js ------

import {getData} from './functions';

let result = getData(arg1,arg2,arg3)
console.log(result)

But even I called like this, I get an Error:

//------ scripts.js ------

import {getData} from './functions';

let result = awiat getData(arg1,arg2,arg3)
console.log(result)

"Uncaught SyntaxError: Unexpected reserved word"

23 thoughts on “fetch function returns promise instead of object”

  1. getData is a async functions and returns a Promise and await is only allowed inside async function.

    export async function getData(arg1,arg2,arg3) {
      try {
        const response = await fetch(proxyUrl + targetUrl, requestOptions)
        return await response.json()
      } catch(err) {
        console.log(err)
        throw err
      }
    }
    
    import { getData } from './functions';
    
    getData(arg1,arg2,arg3).then(result => {
      console.log(result)
    })
    
    

    OR this way

    import { getData } from './functions';
    
    const print = async () => {
      const result = await getData(arg1,arg2,arg3)
      console.log(result)
    }
    
    print()
    
    
    Reply
  2. Instead of explicitly promise-based code with .then() and .catch(), use a try/catch block and an actual return statement in an async function, :

    export async function getData(proxyUrl, targetUrl, requestOptions) {
        try {
            let response = await fetch(proxyUrl + targetUrl, requestOptions);
            return response.json();
        } catch (error) {
            console.log('error', error);
        }
    }
    

    Of course this function still returns a Promise. Every async function does. Promises never actually goes away, async/await only hides them. It’s syntactic sugar. This is important: You cannot return a value from an asynchronous function, no amount of syntactic sugar can change that fact.

    So when you call it, either await it in another async function

    async function main() { 
        var data = await getData(...);
    }
    

    or use Promise semantics in a regular function:

    function main() { 
        getData(...).then(data => ...);
    }
    
    Reply

Leave a Comment