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
Related
This question already has answers here:
How can I access the value of a promise?
(14 answers)
Closed 3 months ago.
I am just trying to find out what in the world is going on here when trying to resolve the promise. Like my code below, I have been trying to take care and resolve the promise but it is just being a pain at this point even after searching for the answers all over.
const getTrades = async () => {
const accountId = accounts && accounts.find(account => account.type === 'EXCHANGE').id;
await getTradesInfo({ accountId: quadAccountId });
};
const pending = getTrades().then(res => { return res });
const resolved = pending.then(res => { return res });
console.log(resolved);
So for some reason, the resolved variable above is still showing a pending object.
your code is still asynchronous, your console log won't wait for your promise to be executed.
here a possible solution:
const getTrades = async () => {
const accountId = accounts && accounts.find(account => account.type === 'EXCHANGE').id;
return getTradesInfo({ accountId: quadAccountId });
};
getTrades.then((res)=> <here can use your console.log> )
or wrapping it with async/await:
const getTrades = async () => {
const accountId = accounts && accounts.find(account => account.type === 'EXCHANGE').id;
return getTradesInfo({ accountId: quadAccountId });
};
(async ()=> {
const result = await getTrades();
console.log(result)
})()
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 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))
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 3 years ago.
I have problems in returning the result of a promise to a variable. The only way that works for me is making a console.log, but it's not what I want.
const getAnimeVideo = async (id: string, chapter: number) => {
const BASE_URL = `${url}${id}/${chapter}/`;
const browser = await puppeteer.launch() ;
const page = await browser.newPage();
await page.goto(BASE_URL);
const elementHandle = await page.$('.player_conte');
const frame = await elementHandle.contentFrame();
const video = await frame.$eval('#jkvideo_html5_api', el =>
Array.from(el.getElementsByTagName('source')).map(e => e.getAttribute("src")));
return video;
}
getAnimeVideo('tokyo-magnitude-80' , 1)
.then(res => console.log(res)); // It shows me the data correctly.
const T = getAnimeVideo('tokyo-magnitude-80' , 1)
.then(res => {
return res; //Promise { <pending> }
})
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());