This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I need to fetch some JSON data from an API and assign the result to a variable. I can see the array of data in the console, but [abc] is always set as a Pending promise.
I've tried to assign [abc] instead of logging [data] or simply returning [data] but it's not working.
Ideally, I would also want to stop the execution of the following code until I get the required data but with the code I have, the text gets logged before the data
async function fetchData()
{
let response = await fetch('API');
let data = await response.json();
data = JSON.stringify(data);
data = JSON.parse(data);
return data;
}
let abc = await fetchData()
.then(data => console.log(data));
console.log('This should not be logged if 'abc' does not have the data i need')
(data => console.log(data)) ..>> here the data is the array I need but I have no idea on how to assign on a variable.
I've looked for many solutions on the internet but I couldn't find anything that could help.
EDIT 1:
If I assign:
let abc = await fetchData()
without the then statement it throws me this error:
Uncaught SyntaxError: await is only valid in async function
If I then remove the await keyword it returns Promise without having it resolved.
In order for await keyword to work, it must sit inside a async function. So you need to wrap your code in a async function first, let's say a main function, then call it. Example:
async function fetchData() {...}
async function main() {
let abc = await fetchData();
console.log(abc);
}
main();
it should be like this
async function fetchData(){
let response = await fetch('API');
let data = await response.json();
data = JSON.stringify(data);
data = JSON.parse(data);
return data;
}
let abc = await fetchData(); // here the data will be return.
console.log(abc); // you are using async await then no need of .then().
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
So, I want to use fetched data from an API in my app, but I cannot store the fetched data outside of async function getapi(), but if I use all other functions while staying inside that getapi() function, they are working fine but I want to store the fetched data outside of that function to make my code more readable and clear.
var mdata;
const api_url = "https://api.jsonbin.io/b/602998b0f460fe73a1967fe0";
async function getapi(url) {
const response = await fetch(url);
data = await response.json();
mdata = data;
}
getapi(api_url);
console.log(mdata);
In the way you're executing your code you're not waiting for the async function to finish.
Your code should look something like this.
Learn more about promises here link
var mdata;
const api_url = "https://api.jsonbin.io/b/602998b0f460fe73a1967fe0";
async function getapi(url) {
const response = await fetch(url);
data = await response.json();
mdata = data;
}
getapi(api_url).then( function(){
console.log(mdata);
}
);
I don't understand why i get Promise { <pending> } since i used async/await
this is my code
const fetch = require("node-fetch")
function getRandomPokemon() {
var pokemonID = Math.floor(Math.random() * 851);
console.log("The Pokemon Id is " + pokemonID);
return pokemonID
}
async function getJSON() {
let response = await fetch('https://pokeapi.co/api/v2/pokemon/'+ pokemonID);
var json = await response.json
}
var pokemonID = getRandomPokemon()
var json = getJSON()
console.log(json)
All async functions return a promise - always. Using await inside an async function suspends the execution of that function until the promise you are awaiting resolves or rejects, but an async function is not blocking to the outside world. An await does not suspend execution of the whole js interpreter.
At the point of the first await in the async function your function returns a promise back to the caller and the caller continues to execute. That promise is then resolved or rejects when the function eventually completes its work sometime in the future.
I don't understand why i get Promise { } since i used async/await
Because all async functions return a promise.
There are numerous issues in your code:
Your getJSON() function has no return value. That means that the promise it returns resolves to undefined so there's not way to communicate back its value.
await response.json needs to be await response.json().
pokemonID should be passed as an argument, not just stuffed into a higher scoped variable.
When calling getJSON(), you have to use .then() or await on it to get the resolved value from the returned promise.
You may also notice that your getJSON() function has no return value. That means that the promise it returns also resolves to undefined. And, await response.json needs to be await response.json().
Your code needs to be more like this:
async function getJSON(id) {
const response = await fetch('https://pokeapi.co/api/v2/pokemon/'+ id);
const json = await response.json();
return json;
}
const pokemonID = getRandomPokemon();
getJSON(pokemonID).then(data => {
console.log(data);
}).catch(err => {
console.log(err);
});
Three problems:
getJSON() doesn't return anything. It needs to end with return json;.
Declaring a function async makes it return a promise. If you want to get the return value directly rather than a promise, you have to call it with await getJSON(). You can only do that if you're calling it from another async function.
You need to call response.json: var json = response.json();
Just a few changes
Add the return statement to the getJSON() function
Use the .json() function to get the json from the response in the getJSON()
One way to handle a promise is to use .then(). You could also use await but make sure that it's scoped inside an await block.
const fetch = require('node-fetch');
function getRandomPokemon() {
var pokemonID = Math.floor(Math.random() * 851);
console.log('The Pokemon Id is ' + pokemonID);
return pokemonID;
}
async function getJSON() {
let response = await fetch('https://pokeapi.co/api/v2/pokemon/' + pokemonID);
var json = await response.json();
return json
}
var pokemonID = getRandomPokemon();
getJSON().then((json) => {
console.log(json);
});
response.json should be a function.
On your getJSON function definition, you are doing await response.json.
Change it to await response.json().
Notice the parenthesis after json().
Since the getJSON function returns promise, you have to await the response
On your second last line, add var json = await getJSON();
furthermore, in order to use await, you must wrap your code in an async function
Wrap your last and second-last line in an async function
async function resolveJSON(){
var json = await getJSON(); // waits for the promise to fulfill
console.log(json);
}
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 load an array of memberdata into a javascript variable so that I can operate on it from within several different functions. After giving it the old college try, I am lost.
I understand the need for asynchronous functions so as not to block the main thread but the only way I have been able to populate a global variable is by storing the function result to session.Storage and then calling it from there in other functions. While this works it seems like an extra step.
async function fetchMember($vid) {
let options = {
method: 'POST',
async:false,
body: JSON.stringify({vid: $vid}),
headers: {
'Content-Type': 'application/json', // sent request
'Accept': 'application/json' // expected data sent back
},
}
let response = await fetch('getMember.php', options);
let $member = await response.text();
sessionStorage.setItem("member", $member)
return ($member); // this is a promise because it is in an async function
} //end of function
fetchMember("999999").then ($dog=> console.log ("Then = " + $dog))// $dog is a promise
console.log ("Member = " + $member); // undefined
$member = session.Storage ("member") // work as expected
I can ".then" log the result of the promise to the console but for the life of me I can't figure out how to store it in a global variable.
As mentioned by #epascarello you are not returning your promise from the then block. A simple (maybe hacky) solution could be to wrap your program in an async function then await the response from your fetchMember function. I made a simple jsFiddle with this in practice.
It is not perfect but it should help you get where you need to go!
JsFiddle: https://jsfiddle.net/3q98gx2t/
(async () => {
// Get the data out of the fetchMember function
// It is in the scope of the overall self executing function.
let test = await fetchMember();
async function fetchMember($vid) {
let options = {
method: 'GET',
}
let response = await fetch('https://api.coindesk.com/v1/bpi/currentprice.json', options);
let $member = await response.text();
return $member; // this is a promise because it is in an async function
} //end of function
console.log("Member = " + test); // undefined
})();
The problem with the whole then/catch system is that it will always return a promise so, depending on your project, you will end up in a long ass chain of .then(data => something).then(data => something).
For this example I have used a GET request to the Bitcoin API but the principle remains. Just swap your options back in and it should work.
As you can see I have removed the session storage call.
JSFiddle example https://jsfiddle.net/xo15vet6/
I want to process the Async function result to another function, Once user click the save button I should process global variable value , how can I achieve it.
getMovieAsync is a function, not a promise
I think this will work:
let finalMovies = "";
async function getMovieAsync() {
const response = await fetch('https://www.omdbapi.com/?s=batman&y=&plot=short&r=json');
const movies = await response.json();
return movies;
}
finalMovies = getMovieAsync();
console.log("final movies " + finalMovies);
For what I see you should be already be doing it, in the case you wanted to assign the value to finalMovies, what is happening is that the second console.log is getting executed right after the call to that is asynchronous function so it will execute and then go to the next line (the console.log), but the console.log that is in the .then will only get there if the async operation resolves. If somehow it it rejects it will not even print that line. Because it will go to the .catch of the async function.
let finalMovies = "";
async function getMovieAsync() {
var response = await fetch('https://www.omdbapi.com/?s=batman&y=&plot=short&r=json');
var movies = await response.json();
return movies;
}
async function getMovies(){
try{
finalMovies = await getMovieAsync();
console.log("final movies', finalMovies);
}catch(exception){
console.log('Something went wrong')
}
}
if you pay attention I changed the second console log because if you do the "string" + (something that might be an object or array of object) it will print you the [object Object] because it will run the default toString() for that.
This question already has answers here:
Why is my asynchronous function returning Promise { <pending> } instead of a value?
(9 answers)
Closed 3 years ago.
I'm trying to make a bunch of request an await to all of them to be completed with a Promise.all() function, but instead of doing manually all the fetchs like this:
var data = await Promise.all([
fetch('https://jsonplaceholder.typicode.com/posts').then((response) => response.json()),
fetch('https://jsonplaceholder.typicode.com/albums').then((response) => response.json()),
fetch('https://jsonplaceholder.typicode.com/users').then((response) => response.json())
]);
i want to make it dynamic, to make N fetch requests like this:
let promiseList = [];
try {
for (let url of requestUrls) {
promiseList.push(fetch(url).then((response) => response.json()));
}
var data = await Promise.all(promiseList);
But i get this error Uncaught SyntaxError: await is only valid in async function in the await Promise.all() line, if i delete the await, i get a PromiseĀ {<pending>} and
(index):79 error:TypeError: data is not iterable
This is my full code: https://jsfiddle.net/ham7g82e/1/
What i'm missing to get the data from those fetchs?
Don't use await, instead use Promise.then
Promise.all(promiseList).then(data => {
document.getElementById("result").innerHTML = data;
console.log(data);
for (var i of data) {
console.log(`RESPONSE ITEM \n`);
for (var obj of i) {
console.log(obj);
}
}
});
To use await, it needs to be part of an async function.
async function functionName() {
//You can use await in here, because you used the async keyword
}
If the function where are executing this code is not async, you could just use the .then() to get the values from the promises. There is not need to use await.
Check this documentation: Promise.all()