So my code here return a Promise and since I'm using then
syntax I don't know why that happens :-??
fetch('someurltoAJsonFile.json')
.then(function(response) {
console.log(response.json());});
Promise.then fetch is an asynchronous function. What this function returns is a Promise object. This kind of object has three possible states: pending, fullfilled and rejected.
You can use the return value from the Promise object ONLY in a async function. You should do all the stuff that you'd like to do with the return result in a printAddress () async function.
Approach: You need to first declare a simple function (either a normal function or an arrow function (which is preferred)). You need to create an asynchronous function and then further you need to return the promise as an output from that asynchronous function.
Promise { <pending> } It's happening because the Javascript code always executes synchronously, so the console.log () function starts immediately after the fetch () request, not waiting until it is resolved. In the moment when console.log () function starting to run, a Promise that should be returned from a fetch () request is in a pending status.
response.json() in node-fetch library also returns a promise, instead try
fetch('someurltoAJsonFile.json')
.then(response => response.json())
.then(data => {
console.log(data)
});
you can look up more details about it here
EDIT:
It seems that the returned response wasn't in the valid json, so for the sake of completeness here is a code for text
fetch('someurltoAJsonFile.json')
.then(response => response.text())
.then(data => {
console.log(data)
});
The function given as then
parameter will be executed asynchronously (sometime in the future when your server returns a response), but then
itself return Promise immediately (in synchronous way) by its definition
If you want to code looks less nested (more as synchronous code) you can use await but you must opaque whole code with async function
async function load()
{
let response = await fetch('someurltoAJsonFile.json');
let data = await response.json();
console.log(data);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With