0

Suppose there's this pseudo code:

async function _make_api_call({method,data,endpoint}){
    var myHeaders = new fetch.Headers();
    myHeaders.append("Content-Type", "application/json");

    var requestOptions = {
        method: method,
        headers: myHeaders,
        redirect: 'follow'
      };
    if (method == POST_METHOD){
        requestOptions['body']= data
    }
      
    let response = await fetch(endpoint, requestOptions).then(response => response.json())
    .then(response => response)
    .catch(error => console.log('error', error));
    console.log(response); //prints actual response
    return response;
}


function test(){
   response=_make_api_call(params);
   console.log(response) //prints Promise<pending>
   return response;
}

console.log(test) //Prints undefined

Output is:

Promise<pending>
undefined
//actual response

Functionaliy i want to implement here is (sort of like synchronous.. like other languages eg. python)

//actual response
//actual response
//actual response

i.e. response=make_api_call(params); stores actual response and not promise..

main reason why I added await in _make_api_call was so that it doesn't return response till promise is fully resolved and we have actual response itself stored in test() but why is it returning promise instead?

I know I can do test.then(//print data)

But why is it returning promise despite having await and how to fix this?

I'm new to promises and nodeJS..

  • 4
    `async` functions, [by definition](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#return_value), return a Promise. And once you've got a Promise, there is no way to turn it into a non-Promise value - again by design. If you think about it, you'll see it doesn't make any sense - if I've got to "wait for" a value, then I've got to wait for it, you can't get from that to a value "now". – Robin Zigmond Jun 21 '21 at 19:16

0 Answers0