We're trying to get the response JSON from a GET request.
When we print result
from inside the get
function, the JSON gets printed out like you expect.
However, when we return it and then try to print it, we get a Promise
stuck on <pending>
.
Below is our code:
"use strict";
async function get(url) {
let response = await fetch(url);
if (!response.ok) {
throw new Error(`An error occured: ${response.status} ${response.statusText}`);
}
let result = await response.json();
console.log("result inside function", result);
return result;
}
let url = "OUR_URL";
let result = get(url);
console.log("result outside function: ", result);
Below is the output:
result outside function: Promise {<pending>}
result inside function {success: true, statusCode: 200}
Based on the order of the output statements above, the outer code is executing first before the code inside the function gets resolved despite having await
inside the function.
Unfortunately, the outside code isn't in an async
function, so it can't use await
.
However, when we use then()
outside the function, we are able to get the response just fine:
get(url).then(result => {
console.log("result outside function, inside then: ", result);
});
Below is the output:
result inside function {success: true, statusCode: 200}
result outside function, inside then: {success: true, statusCode: 200}
Above, the order of the output statements is as expected, with the inside one executing first before the ouside one.
We have seen this answer, but it hasn't clicked for us on JavaScript.
We have three questions:
What is JavaScript doing here, exactly?
Is there a way to get the response outside the function without having to use
then()
?2.1. If the answer to the above is no, is there a way to get the response from inside
.then()
and expose it outside?