understanding async and await in JavaScript [duplicate] - javascript

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

Related

why doesnt i get the variable? [duplicate]

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

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

Javascript Async/await with axios resolve pending [duplicate]

This question already has answers here:
Why is my asynchronous function returning Promise { <pending> } instead of a value?
(9 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I have a simple, question. I try to found a solution on web but every try failed.
I have this code:
const getSideBarMenu1 = async () => {
let myArray = []
await axios.get('https://jsonplaceholder.typicode.com/posts').then(res => {
console.log('res1', res)
myArray = res.data
}).catch(err => console.log(err))
console.log('myArray', myArray)
return myArray
}
And when I use this function like this:
const useFunction = getSideBarMenu1()
console.log('useFunction', useFunction)
the result of console log is:
useFunction Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(100)
How to save the PromoseResult inside a variable?
Thank you everyone!
You need to wait for the promise to fulfill, before accessing its result:
const useFunction = await getSideBarMenu1()
getSideBarMenu1 is async that returns a Promise, meaning you have to await it.
const useFunction = await getSideBarMenu1();
You can also use .then()
You can also return data directly from getSideBarMenu1 function:
const getSideBarMenu1 = async () => {
const {data} = await axios.get('https://jsonplaceholder.typicode.com/posts')
return data
}
const useFunction = await getSideBarMenu1()
You forgot a little keyword here.
const useFunction = await getSideBarMenu1()
console.log('useFunction', useFunction)
article source: https://jasonwatmore.com/post/2020/04/30/vue-fetch-http-get-request-examples
video source: https://www.youtube.com/watch?v=NHfyF0B4y8E

Ноw to return result from promise? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I know its may be dumb question, I've already read similar questions. Tryed to do this but it not work at all in my code. I got function
const request = async (url) => {
const response = await fetch(url);
const result = await response.json();
return result;
}
it return another promise
Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(100)
I need "array" NOT "promise". Tried to use Promise.resolve() but looks like I have no idea how to use it here.. all my attempts not work. always get error "resolve is not defined". Please just help if you know how to do it.
Here is a working example of how this might work end to end:
const request = async (url) => {
const response = await fetch(url);
return response.json(); // no need to await the parsing of json
}
// now we call the function, I'm using a self-invoking function here but I assume you will run this code in your own function. Just make sure it's also an `async` function.
(async () => {
const yourData = await request('https://bronzies.com/api/version');
// we have to await the async function to resolve before we can see the data
console.log(yourData);
})();
Another way to get the data out is to use then instead of async/await
request('https://bronzies.com/api/version')
.then( yourData => console.log(yourData))
.catch( error => console.error(error));
Hope this helps
You don't need to call await again. The first await does resolve the promise, and then response.json() parses the json and returns it as resolved
const request = async (url) => {
const response = await fetch(url);
return response.json();
}
Calling the above function:
const results = await request(url)
console.log(results)
OR
request(url).then(results => console.log(results))

Promise still pending even though using .then() [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I am using axios to retrieve data from my BackEnd but the promise is still pending.
I have used .then() even async and await. I am using .then(res => res.data) since i know that every promise has "data" key holding the retrieved data and that after that it will be returned this way. I also binded the function in the constructor!
async getTrackInfo() {
return await axios.get('http://localhost:60231/api/values')
.then(res => res.data);
};
componentDidMount() {
const data = this.getTrackInfo();
console.log(data);
this.setState({
tracks: data
});
}
But unfortunately, it returns undefined.
Following code would work:-
async getTrackInfo() {
return await axios.get('http://localhost:60231/api/values')
.then(res => res.data);
};
async componentDidMount() { // Make this function async
const data = await this.getTrackInfo(); // add await here
console.log(data);
this.setState({
tracks: data
});
}

Categories

Resources