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[]> {
}
Related
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/
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?
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);
})();
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?
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 5 years ago.
I created a Javascript function that returns a boolean value. One of the lines of code in the function invokes a REST call. I didn't realize that call was going to be asynchronous when I coded it. So, basically, the method always returns 'false' when I do something like:
if(isDataValid()) ...
I could move the actions in the calling function to the success function, but I was trying to create a reusable method. I'm using jQuery and Everest. I have not learned anything about Promises yet and I'm fairly new to callback programming.
Here's boiled down version of my method:
function isDataValid(){
// Read data from Local Storage
// Create object from data
// Flag variable to capture result
var isValid = null;
restClient
.read('/my/url', model)
.done(function(response)
{
// 'Good' response, set flag to true
isValid = true;
})
.fail(function(response)
{
// 'Bad' response, set flag to false
isValid = false;
});
return isValid;
}
How should I make an async call and return true/false?
Function should be marked as async in order for await to be used inside.
Since you didn't use response, I removed it.
If you need response, then
var response = await restClient.read('/my/url/', model);
You should use try/catch to handle errors.
Here is the end result:
async function isDataValid(){
var isValid = null;
try {
await restClient.read('/my/url', model);
isValid = true;
} catch(err) {
isValid = false;
}
return isValid;
}
In the end to call isDataValid you should also use await in front of the function call. So it will looks like that:
if(await isDataValid()) { ... }
Since await can be used only inside async functions, function where isDataValid is called should be also marked as async. This way you should update all the chain of function calls to be used with await.