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)
})
``
Related
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}`)
}
}
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.
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);
}
})
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);
});
This question already has answers here:
fetch resolves even if 404?
(5 answers)
Closed 4 years ago.
I have an array of promises that contain simple api url for fetch a github users. I try to make it failed with putting a wrong url in one of my value of array, but it always resolve?
Here i provide a link to my test case
https://jsbin.com/lapibalate/edit?js,console
let urlMap = [
{
url: 'https://api.github.com/users/andreepratama27',
},
{
url: 'https://apiiiiiii.github.com/users/rizalfakhri12'
}
]
let promises = urlMap.map(v => fetch(v))
Promise.all(promises)
.then(res => console.log('RESOLVED'))
.catch(err => console.log("REJECTED"))
That's because your doing a fetch not towards the URLs you specified, but towards [object Object] on your current URL (as the v property is an object, not a string). Change the map to read the url property and it will be rejected:
let promises = urlMap.map(v => fetch(v.url))
Complete example with changes:
let urlMap = [
{
url: 'https://api.github.com/users/andreepratama27',
},
{
url: 'https://apiiiiiii.github.com/users/rizalfakhri12'
}
]
let promises = urlMap.map(v => fetch(v.url))
Promise.all(promises)
.then(res => console.log('RESOLVED'))
.catch(err => console.log("REJECTED"))
From the documentation:
The fetch specification differs from jQuery.ajax() in two main ways:
The Promise returned from fetch() won’t reject on HTTP error status
even if the response is an HTTP 404 or 500. Instead, it will resolve
normally (with ok status set to false), and it will only reject on
network failure or if anything prevented the request from completing.
So thats why.