async return to a variable [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
In my code i have an async function that retuns an object i have to work with it outside the function but i dont really know how to assign it to a variable, I know this post might be a duplicate but i read the others and tried and it doesn't work.
async function name(url) {
//function
return {
item1:{ ....},
item2:{....}
}
}
let p = name(url);
console.log(p);
it returns in the console:
Promise { <pending> }
but it doesn't log the output
How can i fix that?

Promises are async. You need to get the result using
A callback, specified to the then method of the promise.
name(url).then(p => console.log(p))
Or use an async context and use the await keyword:
(async(){
let p = await name(url);
console.log(p);
})();

Related

How to return a value from a promise which isn't a pending promise: d3.js, Javascript? [duplicate]

This question already has answers here:
async/await implicitly returns promise?
(5 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I am relatively new to asynchronous javascript programming. When using the d3.scv function from the d3 library, I ran into an issue where when awaiting the results of the promise from d3.csv inside a async function scope, I can directly access the resolved value, but when I return this resolved value I get a pending promise.
Code
async function generateCountryData(){
let csvData = await d3.csv("./data/data.csv", (d) => {
return {
"id" : +d["id"], // The '+' turns a string into a number
"country" : d["name"],
"faction" : +d["overlord"]
}
});
let dataArray = csvData.map(Object.values);
// LOG 1
console.log(dataArray);
return dataArray;
}
// LOG 1: Array(58)
// Returns: PromiseĀ {<pending>} "fulfilled"[[PromiseResult]]: Array(58)
async function func1() {
let result = await generateCountryData();
// LOG 2
console.log(result);
return result;
}
// LOG 2: Array(58)
// Returns: PromiseĀ {<pending>} "fulfilled"[[PromiseResult]]: Array(58)
Since I dont want to define a new async function each time I want to access this array, I want to know how I can return a defined resolved value which isn't a pending promise.
It's annoying, but this is how it works. Anything that needs access to the result of an asynchronous operation must itself be asynchronous.
So while there's different patterns for dealing with this (callbacks, observers, promises), you can't get around this so best to embrace it.
You can't turn async code into non-async code. An interesting article about this:
https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function/

How can I use the return of an async function as a parameter? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I have this function
const totalJueces = async(id, idPost) => {
try{
const res = await axios(`${process.env.REACT_APP_PJUD_URLBASE}agenda/fullList/${id}/${idPost}`, { 'timeout': 30000 })
console.log(res.data.listaJuecesAsignadosCausa.length)
}
catch(error){
console.log(error)
}
}
If I console.log(res.data.listaJuecesAsignadosCausa.length) it's actually giving me the correct response, in this case an integer (I need to know the specific number of arrays in that request)
But If I try to use this function with a return, it returns a Promise pending.
How can I use the correct number to use it as a dynamic parameter in a loop of items?
Promises will always log pending as long as the results are not resolved yet. You must call .then on the promise, or alternatively, await the promise, to capture the results regardless of the promise state (resolved or still pending).
see Why is my asynchronous function returning Promise { <pending> } instead of a value?

How to return data from await/async loops? [duplicate]

This question already has answers here:
async/await implicitly returns promise?
(5 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have several async http requests I need to make to an API to fetch some data. It's pretty simple to setup in a loop in a function like this:
async function fetchData() {
let data = {}
for (const asset of someAssets) {
try {
data[asset.id] = await library.fetchSomeData(asset.id)
} catch (err) {
console.error(err)
}
}
return data
}
let data = fetchData()
console.log(data)
The problem here is that the last console.log(data) comes back as a pending Promise instead of the data. How do I fix this issue? Do I need to wrap my "main" code (at the bottom) in a async function as well? At what point does my entire project just need to wrapped around a async function?

promise async data extract issue [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
loadcsv(file: File): string[] {
let csvRecordsArray: string[];
this.parse(file).then((p) => {
console.log(p);
csvRecordsArray = p as string[];
});
console.log('mydata', csvRecordsArray);
return csvRecordsArray;
}
console.log inside the then prints the data I need. Nothing wrong with the Promise. However, since it does not block my second console.log has undefined in csvRecordsArray. So I read up on Promises and learnt that I need to await. As soon as I type async to make loadcsv async ts lint says:
Type 'string[]' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value.
Please help me get out of this tailspin.
You can change the implementation of your loadcsv function by making it async. For that, you'll have to await the function call to this.parse.
Also since async functions are expected to return a Promise, you'll have to change the return type of your function to Promise<string[]>
Change your implementation like this:
async loadcsv(file: File): Promise<string[]> {
let csvRecordsArray: string[];
csvRecordsArray = await this.parse(file);
console.log('mydata', csvRecordsArray);
return csvRecordsArray as string[];
}
If your function is an async function because you need to use await, those functions always return a Promise.
So the correct signature for this is:
loadcsv(file: File): Promise<string[]> {
}

Extracting JSON data from public API, returning a promise [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I want to extract an array from the public API, and all I'm receiving is a promise. How can I return the array from the API, outside my function?
Please have a look at the code I'm trying to implement:
var getMov = function() {
return fetch('http://localhost:8080/api/projects')
.then((response) => response.json())
.then((responseJson) => {
JSON.parse(responseJson.movies);
return responseJson.movies;
})
};
console.log(getMov());
Let me know if you have any ideas, how to solve this promise issue.
You just have to use the then method again.
getMov().then(function(movies) {
// do smth with movies
});
According to the promises specs the argument of the onFulfilled function will be the returned value from the last exectuted onFulfilled method, which is your case return the movies.

Categories