Fetch API returning "undefined" [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I am currently learning how to work with APIs, and I am having a little trouble with fetching the data from an API. The code below successfully gets a response but does not actually get any data from the server. How do I go about solving this?
const onClick = () => {
fetch(
`https://collectionapi.metmuseum.org/public/collection/v1/objects/45734`
)
.then(res => {
if (res.ok) {
console.log(res)
console.log('SUCESSS')
} else {
console.log("Not Successful")
}
})
.then(data => {
if (data) {
console.log(data)
} else {
console.log("undefined data")
}
})
.catch(error => console.log('ERROR'))
console.log(results);
}

The promise .then methods can be chained in a way each chained then methods will receive the returned value of the previous one. In your case, the first one does not return any values, making the second one receiving nothing, also well known as undefined.
As the url your code is calling return json content, you should return after loging success the result of res.json().
This will read the stream of the response body and parse it as json, using a promise.

Related

How can you limit the speed of .map() for the sake of fetch()? [duplicate]

This question already has answers here:
How to throttle my JS API fetch requests, using the rate-limit supplied by the host?
(3 answers)
How can I rate limit how fast a javascript function allows itself to be called?
(12 answers)
Closed 8 months ago.
I'm working on an app where I need to .map() over some wallets, and in the process use the wallet data to make a fetch call, then return a new object with the original wallet data spread into it and finally add the new information from the fetch. (Getting a balance from https://btc1.trezor.io/api/v2/xpub/{my-btc-xpub})
I am running into an issue where .map() hits the fetch calls so fast, that it causes it to fail on the 2nd item.
I've found just placing the fetch in the a setInterval() with 1000 ms is plenty of time for it to fetch repeatedly.
However, setInterval() with 500ms is reproducing the same 503 error my .map() fetch()es have been returning to me.
All of my code works until I've added a second wallet to my database, causing the map to run at least twice.
Is there a way to regulate how fast these fetch()es will be made? Is there a better way of going about this problem?
Related working code:
setInterval(() => {
fetch(`https://btc1.trezor.io/api/v2/xpub/${xpub}`)
.then(response => response.json())
.then(data => console.log(data))
}, 1000)
Related broken code:
static async getWalletBalances(_accountsList) {
try {
let accountPromises = _accountsList.map(async account => {
let walletPromises = account.wallets.map(async wallet => {
//breaks right here!!!
let balance = await fetch(`https://btc1.trezor.io/api/v2/xpub/${wallet.walletXpub}`)
/*
this response becomes a 503 html page response instead of json
after the first wallet data is fetched
*/
.then(response => response.json())
.then(data => data.balance)
return { ...wallet, balance: balance }
})
let wallets = await Promise.all(walletPromises)
return { ...account, wallets: wallets }
})
let accountsList = await Promise.all(accountPromises);
return accountsList
} catch (error) {
console.log(`Unable to fetch balances: ${error}`)
}
}

Javascript fetch POST call doesn't wait for resolve [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I am working on a Python dashboard with FastAPI and Javascript. I have created a POST call returning an URL in FastAPI, which I am trying to fetch with Javascript and pass to the player. The output of this POST call is JSON. I am trying to assign the value of a certain key to the laURL variable. The problem is that even though I am using await and async function, Javascript is not really waiting for resolving the response and the second function is executed before the completion of the laURL assignment.
async function fetchLicense(playbackURL) {
try {
let response = await fetch(apiURL, {
method: "POST"
});
if (response.ok) {
let result = await response.json();
let laURL = JSON.parse(result).la_url;
return await laURL;
} else {
console.log("POST Error: ", response);
}
} catch (error){
console.log("POST Error: ", error);
}
}
And then I am using the returned value in another function:
function fetchSource(playbackURL) {
let laURL = fetchLicense(playbackURL);
const source = {
dash: playbackURL,
drm: {
widevine: {
LA_URL: laURL
},
immediateLicenseRequest: true
}
};
return source;
I have checked and tried a couple of different solutions, but nothing seems to be working.
This should be really something straightforward, but unfortunately, the solution isn't so obvious to me.
Javascript async/await is just syntactic sugar for using Promises. fetchLicense hence returns a promise. You can use Promise.then(/* callback */) to specify what should happen when data is resolved.
If you're unfamiliar with this, the following link might help you understand how it works exactly: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Data is not pushed in an array [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I got data from API and tried to push it in an array, but when I print it, it's empty. The data is JSON.
fetch("url")
.then((response) => response.json())
.then((data) => sohawnID.push(data.id))
console.log(sohawnID)
//output: []```
this is because synchronous behavior of node js. what you need is to put you api call method inside a Promise function and then call it using async await. By this way program 1st wait for api response and then push data to your array
The reason it prints empty is console.log(sohawnID) called before the promise fulfil meaning you are trying to print result before it arrives. You can do this:
fetch("url")
.then((response) => response.json())
.then((data) => {
sohawnID.push(data.id);
console.log(sohawnID)
})
``

Cannot retrieve specific JSON data from API call [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I am trying to use the variable 'myResult' to return specific JSON data. I believe I may have written the 'myResult' variable wrong and I am not querying for the correct data. The path for '[1].show.score'is correct and I will add in screenshots of the JSON data I am trying to call.
When I call for this data, I get returned to me this error:
[![My error][2]][2]
Here is the result of 'url'
[![The returned JSON data from the variable 'url'][1]][1]
Here is my code:
document.querySelector('.myButton').addEventListener('click', function(){
var query = document.getElementById('main').value;
var url = fetch("http://api.tvmaze.com/search/shows?q="+query)
.then(response => response.json())
.then(data => console.log(data));
var myResult = url[1].show.score;
console.log(myResult);
})```
[1]: https://i.stack.imgur.com/lTn8V.png
[2]: https://i.stack.imgur.com/kS7gB.png
You cannot access the data from url the way you are trying to access it with url[1].show.score because url is a promise that you can call .then() and .catch() on, which you already do in order to receive the data.
If you want myResult to use the specific data, you need to use it within the .then() callback
So you may have something like this in the end:
document.querySelector('.myButton').addEventListener('click', function(){
var query = document.getElementById('main').value;
fetch("http://api.tvmaze.com/search/shows?q="+query)
.then(response => response.json())
.then(data => {
console.log(data));
var myResult = data[1].show.score;
console.log(myResult);
}
})

fetch function return Promise <pending> [duplicate]

This question already has answers here:
Why does .json() return a promise?
(6 answers)
Closed 11 months ago.
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());});
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);
}
Debating whether or not this qualifies as an answer, but I ran into a similar situation today that led me to this question even though my problem ended up being environment related.
If you are seeing promise pending and your code is correct and you spend way too much time trying to figure out why the console.log isn't showing, double check that you have "Info" turned on in chrome's dev tools. I only had warnings turned on so I wasn't seeing my console.log.
This code works and show a good way to make a fetch and get the promise without the pending problem.
Run this code in your server if you have cors problem download this extension in google chrome "Allow CORS: Access-Control-Allow-Origin"
async function invoices()
{
let response = await fetch('https://blockchain.info/latestblock?utm_medium=referral&utm_campaign=ZEEF&utm_source=https%3A%2F%2Fjson-datasets.zeef.com%2Fjdorfman');
let data = await response.json();
console.log(data);
return data;
}
invoices().then(data => {
console.log(data);
});

Categories

Resources