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.
Related
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
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I make calendar for my project and need to use seved data from server inside "function CalendarPicker()".
I get data from server as promise and try use it inside "function CalendarPicker()" but always get undefined. How can I force it?
async function _getMeetingsData() {
let response = await fetch('calendar');
let data = await response.json();
data = JSON.stringify(data);
return data;
}
function CalendarPicker() {
//Get meeting data
this.meetingsData = _getMeetingsData();
this._insertNavigationButtons();
this._insertHeaderIntoCalendarWrapper();
this._insertCalendarGridDaysHeader();
this._insertDaysIntoGrid();
this._insertCalendarIntoWrapper();
}
const myCalender = new CalendarPicker();
You need to have an async constructor (arguably odd) or await for your data, because every async function is implicitly a promise, even if it synchronously returns a value ... so:
function CalendarPicker() {
//Get meeting data ... then
_getMeetingsData().then(meetingsData => {
this.meetingsData = meetingsData;
this._insertNavigationButtons();
this._insertHeaderIntoCalendarWrapper();
this._insertCalendarGridDaysHeader();
this._insertDaysIntoGrid();
this._insertCalendarIntoWrapper();
});
}
This works, but if you have any prototype method that needs that data, you better store the promise:
function CalendarPicker() {
//Get meeting data ... then
this._meetingsData = _getMeetingsData().then(meetingsData => {
this.meetingsData = meetingsData;
this._insertNavigationButtons();
this._insertHeaderIntoCalendarWrapper();
this._insertCalendarGridDaysHeader();
this._insertDaysIntoGrid();
this._insertCalendarIntoWrapper();
});
}
CalendarPicker.prototype.doThings = function () {
this._meetingsData.then(() => {
console.log(this.meetingsData);
});
};
Because you have defined _getMeetingsData as an async function, you need to call _getMeetingsData with the await keyword. In that case, you also need to make CalendarPicker an async function. Alternatively, you can call _getMeetingsData within a promise construct in your CalendarPicker 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 am new to node js and I have never worked with promises before so I would greatly appreciate any advice.
I am using an async await function to read a .txt file line by line, it returns an array.
async function processLineByLine() {
const fileStream = fs.createReadStream('input.txt');
const array = [];
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
for await (const line of rl) {
array.push(line)
}
return array
}
I want to create a new instance of a class using this array as an argument, like this:
let variableName = new ClassName(array)
So that I can call functions on this instance of an object and manipulate its state.
I have tried to do this:
async function input() {
var result = await processLineByLine();
return result
}
let variableName = ClassName(input())
variableName.someFunction()
But it fails as the state I am trying to access is undefined and console.log(input()) shows promise pending.
You need to put all the code after the await:
async function input() {
var result = await processLineByLine();
let variableName = ClassName(result)
variableName.someFunction();
}
input().catch(console.error);
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I want to get a "value of Data" from Firebase Realtime Database. You can find my code below:
async function getName() {
const result = await firebase.database().ref('/users/' + user.user.uid)
.once('value').
then(async function(snapshot) {
console.log("SNapshot =>");
console.log(snapshot.val().displayName); // returns "John Doe"
const result2 = await snapshot.val().displayName;
return result2;
});
return result; // returns "Promise Object"
};
It returns "Promise". But i want to get value not promise.
How should i fix my code?
Thanks.
You are mixing up use of async/await with then()/catch(). You should pick one syntax or the other, not both together in this case. You are also trying to use await on something that is not a promise. Just write your function like this:
async function getName() {
const snapshot = await firebase.database().ref('/users/' + user.user.uid).once('value')
return snapshot.val().displayName
}
And call it like this:
const name = await getName()
The getname function is doing async operation so you can do:
try {
await result = getName();
} catch (e) {
throw e;
}
within an async function, or, if you prefer without async :
result.then((res) => console.log(res));