why doesnt i get the variable? [duplicate] - javascript

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();

Related

Where do I need to place await (or possibly .then()) to fix this so that it doesn't return Promise { pending }? [duplicate]

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
})();

fetch function returns promise instead of object [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
async/await always returns promise
(4 answers)
Closed 2 years ago.
I have a function getData in functions.js, when I called in another file, scripts.js it returns promise not an object.
//------ functions.js ------
export async function getData(arg1,arg2,arg3) {
...
let result = await fetch(proxyUrl + targetUrl, requestOptions)
.then(response => response.json())
.catch(error => console.log('error', error));
return result
}
When I call like this I get a Promise:
//------ scripts.js ------
import {getData} from './functions';
let result = getData(arg1,arg2,arg3)
console.log(result)
But even I called like this, I get an Error:
//------ scripts.js ------
import {getData} from './functions';
let result = awiat getData(arg1,arg2,arg3)
console.log(result)
"Uncaught SyntaxError: Unexpected reserved word"
getData is a async functions and returns a Promise and await is only allowed inside async function.
export async function getData(arg1,arg2,arg3) {
try {
const response = await fetch(proxyUrl + targetUrl, requestOptions)
return await response.json()
} catch(err) {
console.log(err)
throw err
}
}
import { getData } from './functions';
getData(arg1,arg2,arg3).then(result => {
console.log(result)
})
OR this way
import { getData } from './functions';
const print = async () => {
const result = await getData(arg1,arg2,arg3)
console.log(result)
}
print()
Instead of explicitly promise-based code with .then() and .catch(), use a try/catch block and an actual return statement in an async function, :
export async function getData(proxyUrl, targetUrl, requestOptions) {
try {
let response = await fetch(proxyUrl + targetUrl, requestOptions);
return response.json();
} catch (error) {
console.log('error', error);
}
}
Of course this function still returns a Promise. Every async function does. Promises never actually goes away, async/await only hides them. It's syntactic sugar. This is important: You cannot return a value from an asynchronous function, no amount of syntactic sugar can change that fact.
So when you call it, either await it in another async function
async function main() {
var data = await getData(...);
}
or use Promise semantics in a regular function:
function main() {
getData(...).then(data => ...);
}

Get data from Javascript fetch and display it in another function [duplicate]

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);
}

await is only valid in async function error for a async function [duplicate]

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.

understanding async and await in JavaScript [duplicate]

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());

Categories

Resources