This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
async/await implicitly returns promise?
(5 answers)
Closed 2 years ago.
Get the value from a function in some other languages is simple like write return something
I can't get how to do it in JS from an async function.
const URL = `https://www.reddit.com/r/all.json`;
async function getPost() {
var list = [];
let response = await fetch(URL).then((res) => res.json());
let childList = await response.data.children;
childList.map((el) => {
let id = el.data.id;
let title = el.data.title;
list.push({
id: id,
title: title,
});
});
console.log(list);
}
var oo = getPost();
If you try the code like this everything work fine. But if to change console.log(list) inside getPOst() to return list and try to console.log(oo) nothing is showing
So... BIG thanks to #nick-parsons
that's the answer:
Oh, so a Promise is being shown. Your async function will wrap the >return value in a Promise, so that's expected. To "extract" the >value/list, you need to use .then(list => // use list here) on the >returned Promise. Or, if you're in a ES module, you can await the >Promise
Related
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)
How can I access the value of a promise?
(14 answers)
Closed 7 months ago.
I found that it's not straight forward to filter a list of values of promises, so I tried the approach in this question (top answer).
The difference is, i'm using this inside useEffect in React.
My results array is empty outside of the async getData function:
// helper function
async function filter(arr, callback) {
const fail = Symbol();
return (
await Promise.all(arr.map(async (item) => ((await callback(item)) ? item : fail)))
).filter((i) => i !== fail);
}
useEffect(() => {
if (!stateData) {
let results = [];
async function getData() {
const res = await filter(data.slice(0, 5), async (item) => {
const boolRes = await myAsyncFunction(item);
return boolRes;
});
// results has data
results.push(...res);
}
getData();
console.log(results) // is empty, but results inside getData has data
}
}, []);
any idea how I can pull the data out of getData safely?
This question already has an answer here:
get data from async function
(1 answer)
Closed 2 years ago.
when i execute this function
const stronaDyskusji = "Some_mediawiki_discussion_page_name";
async function sekcje() {
var zwrot;
const params = {
action: "parse",
page: stronaDyskusji,
prop: "sections",
};
const api = new mw.Api();
await api.get(params).done((data) => {
zwrot = data.parse["sections"];
});
return zwrot;
}
var PIT = sekcje()
console.log(PIT)
the console logs this kind of object.
Is there any way to get this array out of this [[PromiseResoult]]: to for example other variable?
Async functions return promise. If you want to access the result directly you will need to either use await (when you make the sekcje function call) or use the "then" callback on the returned promise.
const PIT = await sekcje();
console.log(PIT);
But for the await to work you will need to put it inside an async function.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return values from async functions using async-await from function? [duplicate]
(3 answers)
Closed 3 years ago.
I'm trying to load a CSV file into my application at the beginning and keep the value in a variable and call it from other functions instead of accessing by then all the time
my code is
var DVizModule = (() => {
let dataset = [];
let _data = async () => {
const data = await d3.csv("data/alphabet.csv");
return data;
}
let data = _data().then(data => {
dataset = data;
return dataset;
})
return {
data: data
}
})();
console.log(DVizModule.data);
it returns
Promise pending proto: Promise
PromiseStatus: "resolved"
PromiseValue: Array(26)
When I write
const t = async function() {
const data = await d3.csv("data/alphabet.csv");
return data;
}
t().then(result => console.log(result))
it returns the file perfectly
I'm trying to access the file content via
DVizModule.data
If you want to access data synchronously, you should declare it as a plain value, not a promise. something like this should do the trick:
const DVizModule = {};
d3.csv("data/alphabet.csv").then(data => DVizModule.data = data);
Note, of course, that DVizModule.data will be undefined until the request is actually complete. If you want to ensure that the value actually is there, you will have to wrap the outer context into an async function and await the data at the very beginning. This way you can both ensure that the value is present when you code accesses it and use it in a synchronous manner.
Hope I got your question right and not trying to resolve the wrong problem ;)
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have 1 function in Nodejs that return a list of recipient:
var recipientList = [];
userService.listUser().then( result => {
var listPSID = result.filter(result => !'279'.includes(result));
recipientList = listPSID.slice();
console.log(recipientList);
});
Now I want to access that list OUTSIDE the function, something likes:
console.log(recipientList[0]);
How can I do that? Thank you all.
If you're using Promises, you cannot access it outside the function. If you use async / await instead, it should work.
async function getList(){
let result = await userService.listUser();
var listPSID = result.filter(result => !'279'.includes(result));
recipientList = listPSID.slice();
console.log(recipientList[0]);
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I got this code using the async/await :
function _getSSID(){
return new Promise((resolve, reject)=>{
NetworkInfo.getSSID(ssid => resolve(ssid))
})
}
async function getSSID(){
let mySSID = await _getSSID()
if (mySSID == "error") {
return 'The value I want to return'
}
}
And getSSID() is equal to this :
Looks like the getSSID() function will always return a promise. How can I get "The value I want to return" in plain text ?
Any help is greatly appreciated.
Declaring a function async means that it will return the Promise. To turn the Promise into a value, you have two options.
The "normal" option is to use then() on it:
getSSID().then(value => console.log(value));
You can also use await on the function:
const value = await getSSID();
The catch with using await is it too must be inside of an async function.
At some point, you'll have something at the top level, which can either use the first option, or can be a self-calling function like this:
((async () => {
const value = await getSSID();
console.log(value);
})()).catch(console.error):
If you go with that, be sure to have a catch() on that function to catch any otherwise uncaught exceptions.
You can't use await at the top-level.