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

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

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

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

javascript/vue.js async/await and .then (promise) not waiting until completion of fetch in login function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I build a login function and check the credentials on my backend-server. I have to wait for the response of the server. I have used an official guide to es7-async-await.js, but it does not work. I have tried everything that async/await and promises give, but it does not work at all. I read all the posts regarding this issue. What am I doing wrong?
My function:
async getCredentials(pUser, pCipher) {
var url = new URL(serviceURL);
var params = {
user: pUser,
p: pCipher
}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
// await response of fetch call
let response = await fetch(url, {
method: 'get',
headers: { }
});
// only proceed once promise is resolved
let data = await response.json();
// only proceed once second promise is resolved
return data;
},
my function call:
this.getCredentials(this.input.username, cipher)
.then(data => this.checkResponse = data.items)
.catch(reason => console.log(reason.message))
console.log("data: ->>>> " ,this.checkResponse);
the result:
data is always empty because the function does not wait
can you put the console.log in the .then?. Is printing something?. If you do a console.log when the data is not received will not print anything.
this.getCredentials(this.input.username, cipher)
.then(data =>
{
this.checkResponse = data.items
console.log("data: ->>>> " ,this.checkResponse);
})
.catch(reason => console.log(reason.message))

How to make `return` respecting async/await in JS?

I'm trying to make this code (a class method) returning a String.
async sign() {
const txt = 'ddddd';
const result = await crypto.createHash('md5').update(txt, 'binary').digest('hex');
return result;
}
The problem is that it ignores await and returns a Promise. This function's returned value is used as a HTTP request header, and while npmlog says it's
apisign: Promise { 'faaa3f1409977cbcd4ac50b5f7cd81ec' }
in network traffic caught by Wireshark I see
apisign: [object Promise]
How do I make return respecting await, or how should I write it so it returns a String?
You should not return the value of an async function as is, since it is a Promise
await for it before serializing it.
An async function always returns a Promise.
If you invoke sign() inside another function then you have to await for it and this requires making the caller function also an async function and so on and so forth.
Eventually, at the top-level code you have to use the regular .then().catch() syntax to wait for the Promise to settle:
sign()
.then((result) => {
// do something with the result (e.g. put it into the response header)
console.log(result);
})
.catch((err) => {
// something wrong happened and the Promise was rejected
// handle the error
console.log(`There was an error: ${err.message || err}`);
});
You will have to await the response of a async function.
const getURL = (title, page) => `https://jsonmock.hackerrank.com/api/movies/search/?Title=${title}&page=${page}`
const callService = async (title, page) => {
let response = await fetch(getURL(title, page));
return await response.json();
}
async function callApi() {
let data = await callService('spiderman', 1);
console.log(data.data.length);
}
callApi();

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