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 ;)
Related
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)
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)
Closed 5 years ago.
I'm using a a js lib called teemojs to get information from riot API using node.js and want to store what i get in a var to call back to later, this code
api.get('euw1', 'summoner.getBySummonerName', playerName)
.then(data => console.log(data.id))
gives me what I want but I'm not able to store it in a var to access globally
any ideas on what i can do
P.S I'm trying to say something like this
api.get('euw1', 'summoner.getBySummonerName', playerName)
.then(data => var Result = (data.id))
You have to declare a variable before your promise like
var myVar;
api.get('euw1', 'summoner.getBySummonerName', playerName)
.then(data => {
myVar = data.id;
console.log(myVar); // myVar is defined
})
console.log(myVar); // myVar is undefined
You can also use async/await like
ty {
const {id} = await api.get('euw1', 'summoner.getBySummonerName', playerName);
console.log(id);
} catch (e) {
console.error(e);
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I know you can access a Promise’s value inside the .then method like the following code:
const Promise = require("bluebird");
const fs = Promise.promisifyAll(require('fs'));
const mergeValues = require('./helper').mergeValues;
fs.readFileAsync('./index.html', {encoding: "utf8"})
.then((data) => {
return mergeValues(values, data); //async function that returns a promise
})
.then((data) => {
console.log(data);
});
In the above example, I’m reading from a file, merging the data with some values, and then logging the data to the console.
But how about returning the value from a function, as you normally would in a synchronous function? If I follow this comment on synchronous inspection, I think the code should look like this:
function getView(template, values) {
let file = fs.readFileAsync('./' + template, {encoding: "utf8"});
let modifiedFile = file.then((data) => {
return mergeValues(values, data);
});
return modifiedFile.then((data) => {
return modifiedFile.value();
});
}
console.log(getView('index.html', null));
But for some reason, it’s not working. All I’m getting in the console is the Promise object itself, not the value. And when I add the .isFulfilled method on modifiedFile, it outputs to true. So I’m not sure what I’m doing incorrectly.
Promises don't work that way. They are asynchronous by nature, so you can't interact with them in the same way you do with synchronous code.
That means you have to use the then method to get at the value:
function getView(template, values) {
let file = fs.readFileAsync('./' + template, {encoding: "utf8"});
let modifiedFile = file.then((data) => {
return mergeValues(values, data);
});
return modifiedFile.then((data) => {
return modifiedFile.value();
});
}
// This won't work
// console.log(getView('index.html', null));
// instead:
getView('index.html', null).then(function (view) {
console.log(view);
});
So I’m not sure what I’m doing incorrectly.
You're not doing anything incorrectly, actually. You just can't use promises like a normal return value from a function. Period.