This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 2 years ago.
I thought it would be easy to find an answer to this, but it wasn't. I'm trying to make an api call from a function and then display the response in a different function. What I've got or what I want to achieve:
async getData() {
const response = await http.get("/api/");
}
async showData() {
const result = await this.getData();
console.log(result);
}
Any help is appreciated!
The getData method shouldn't need to be declared async. Just make showData an async method and await the getData response.
const getData = () => fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json());
const showData = async () => {
const result = await getData();
console.log(result);
}
showData();
Here is the altered code:
getData() {
return http.get("/api/");
}
async showData() {
const result = await this.getData();
console.log(result);
}
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
What is the scope of variables in JavaScript?
(27 answers)
Closed 9 months ago.
im trying to let a variable from JSON and use it in other function but I'm doing something wrong can someone help me?
the code is`
async function githubUsers() {
let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d')
let shipsJSON = await response.json()
}
githubUsers()
shipsJSON.forEach((item) => {
item.forEach((nestedItem) => {
placeCharacter(nestedItem.x, nestedItem.y, "O", myGrid)
// placeCharacter(nestedItem.x, nestedItem.y, 'O', myGrid);
placeRandomCharacter('O', enemyGrid, enemyGridSize);
drawBreak();
})
Because shipsJSON is scoped to the githubUsers function. Maybe the best way is to await that returned data within another async function, and then loop over the data.
async function githubUsers() {
let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d');
return response.json();
}
async function main() {
const shipsJSON = await githubUsers();
// rest of your code
}
main();
Alternatively since fetch returns a promise:
function githubUsers() {
return fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d');
}
async function main() {
const response = await githubUsers();
const shipsJSON = await response.json();
// rest of your code
}
main();
You are using async function, so githubUsers call won't complete before your foreach loop. Also, you are declaring shipsJSON variable inside scope of githubUsers, meaning it won't be available outside it. So you should use return to get it to outer scope. Do it like this:
async function githubUsers() {
let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d')
return response.json()
}
async function fetchAndLoop() {
const json = await githubUsers()
json.forEach((item) => {
item.forEach((nestedItem) => {
placeCharacter(nestedItem.x, nestedItem.y, "O", myGrid)
// placeCharacter(nestedItem.x, nestedItem.y, 'O', myGrid);
placeRandomCharacter('O', enemyGrid, enemyGridSize);
drawBreak();
});
}
fetchAndLoop();
This question already has answers here:
How can I access the value of a promise?
(14 answers)
Closed last year.
const fetch = require('node-fetch');
async function loadPlacesWithImages() {
const responseObj = await fetch("https://byteboard.dev/api/data/places").then(response => response.json())
const placesArray = responseObj.places
for await (const place of placesArray) {
const imageObj = await fetch(`https://byteboard.dev/api/data/img/${place.id}`).then(response => response.json())
place.image = imageObj.img
}
console.log(placesArray)
return placesArray
}
// loadPlacesWithImages()
console.log(loadPlacesWithImages())
I don't understand why the console.log prints the populated array of objects but the function returns Promise { pending }.
I see that there are many questions with answers on this topic, but that still isn't helping me determine how to fix this.
Please help me learn! I would greatly appreciate it!
your function is async but you didn't await it in your last line.
It should be like this:
console.log(await loadPlacesWithImages());
When you call an async function you must use await to await for the function to complete:
// Promise.resolve just creates a promise that resolves to the value
const theAnswerToLife = () => Promise.resolve(42);
console.log(theAnswerToLife()); // Promise { pending }
(async () => { // create async context, not needed with top-level await
console.log(await theAnswerToLife()); // 42
})();
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed last year.
I have this function getData which will read in a list of IDs from a JSON file. the list of IDs is stored to the idsList variable which i need to use inside another function. How do i return the value from this function
function getData(){
fetch("JSONitemIDsList.json")
.then(response => response.json())
.then(data => {
let idsList = data.ids
//return idsList
})
}
function myFunc(idsList) {
//do something with idsList
}
You can approach this in many ways. For example:
// with async / await
async function getData() {
try {
const rawData = await fetch("JSONitemIDsList.json")
const data = await rawData.json()
return data
} catch (err) {
// handle error here
console.log(err)
}
}
async function myFunc() {
const idsList = await getData()
//do something with idsList
}
or
// define first
function myFunc(idsList) {
//do something with idsList
}
function getData(){
fetch("JSONitemIDsList.json")
.then(response => response.json())
.then(data => {
// function call
myFunc(data.ids)
})
}
You can try this:
const reqResponse = fetch("JSONitemIDsList.json")
.then(response => response.json())
// I am not sure, if your data is already in the format that you need, otherwise, you can run one more .then() to format it
}
const getIdList= async () => {
const idList = await reqResponse;
console.log(idList)
// use idList to access the information you need
}
This question already has answers here:
await is only valid in async function
(14 answers)
Closed 2 years ago.
I am fetching 2 URLs at the same time using Promise all but when I am calling this function using await (as getAllURLs is async function) it gives me an error, How can I solve this problem?
const fetch = require("node-fetch");
let urls = ["https://jsonplaceholder.typicode.com/users","https://jsonplaceholder.typicode.com/users"]
async function getAllUrls(urls) {
try {
var data = await Promise.all(
urls.map((url) => fetch(url).then((response) => response.json()))
);
return data;
} catch (error) {
console.log(error);
throw error;
}
}
const response = await getAllUrls(urls)
console.log(response)
Error :
let responses = await getAllUrls(urls)
await is only valid in async function
You can only call await inside an async function, for example:
(async () => {
const response = await getAllUrls(urls)
console.log(response)
)()
Alternatively, you can use a JS engine or compiler with top-level await support.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am trying to understand why promise is not resolved when I am using async and await keywords. Below is the code that I have
var a = 'https://jsonplaceholder.typicode.com/posts';
async function fetchData() {
const response = await fetch(a);
const data = await response.json();
return data;
}
console.log(fetchData());
fetchData function should return actual datas but it always returns a promise object. What am I doing wrong?
I am expect the following output [{userId: 1, name: 'ss'}]after invoking fetchData()
The way async works is that it returns a promise. So what you can do is:
fetchData().then(data => console.log({data}))
And you'll print out your data!
Also, you don't need that line:
const data = await response.json();
because the .json() method is synchronous, and thus there's no need to wait for a promise to be resolved.
So a simpler way to do it would be:
var a = 'https://jsonplaceholder.typicode.com/posts';
async function fetchData() {
const response = await fetch(a);
data = response.json();
// do stuff with data, synchronously
return data;
}
so you want to write code without callbacks, but then what you need is to use fetchData() in an async context, so here's how you can do that:
async function asyncPrint(aPromise) {
console.log(await aPromise);
}
asyncPrint(fetchData);
and if you're evil, you could do:
console.asyncLog = asyncPrint;
so you can run:
console.asyncLog(fetchData());