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);
}
Related
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 5 months ago.
I want to get a value from chrome.storage.local
var storage = chrome.storage.local;
authToken = storage.get('logintoken', function(result) {
var channels = result.logintoken;
authToken=result.logintoken;
console.log(authToken);
return authToken;
});
alert(authToken);
but out of the function authToken is undefined.
function getAllStorageSyncData(top_key) {
// Immediately return a promise and start asynchronous work
return new Promise((resolve, reject) => {
// Asynchronously fetch all data from storage.sync.
chrome.storage.local.get(top_key, (items) => {
// Pass any observed errors down the promise chain.
if (chrome.runtime.lastError) {
return reject(chrome.runtime.lastError);
}
// Pass the data retrieved from storage down the promise chain.
resolve(items);
});
});
}
Used this method and await like
var obj = await getAllStorageSyncData(['logintoken']);
and its worked
https://stackoverflow.com/a/72947864/1615818
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 10 months ago.
This post was edited and submitted for review 10 months ago and failed to reopen the post:
Original close reason(s) were not resolved
How to get the output as a (global) variable from Promises in JavaScript? I found many answers but none helped me in applying to my problem. Specifically, I want to get the data from the code below. It is the node-os-utils library.
cpu.usage()
.then(info => {
console.log(info)
})
EDIT:
I tried to edit the code according to your recommendations, unfortunately I still couldn't find where I'm making a mistake.
I used the async function with await. Now I would like to return and display the value in systemdata, but the output shows Promise <pending>. I figured it's probably because the object is running in the stack before promise completes.
cpu.usage()
.then(cpuPercentage => {
return cpuPercentage +'%';
});
const printCpuUsage = async () => {
const a = await cpu.usage();
return a;
};
let systemdata = {
cpuCount: cpuCount,
cpuModel: cpuModel,
cpuUsage: printCpuUsage(),
// memoryUsage: ,
// CPUtemp: ,
// batteryCycle: ,
// StorageSize:
};
console.log(systemdata)
So I tried to put async directly into the object. With the assumption that this way the object property will have to wait for a promise.
const cpuusage = cpu.usage()
.then(cpuPercentage => {
return cpuPercentage +'%';
});
let systemdata = {
cpuCount: cpuCount,
cpuModel: cpuModel,
cpuUsage: async () => {
const a = await cpuusage;
return a;
},
// memoryUsage: ,
// CPUtemp: ,
// batteryCycle: ,
// StorageSize:
};
console.log(systemdata)
Unfortunately this code output: cpuUsage: [AsyncFunction: cpuUsage]
try this:
// global scope
let globalInfo;
cpu.usage().then(info => {
globalInfo = info;
});
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)
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 Observable/http/async call in angular?
(10 answers)
Closed 4 years ago.
I'm getting valid response value from subscriber when I use below code snippets from two different components.
dataService.ts
insertappFormData(){
return this.http.get('http://localhost:48116/RecuruitmentService.asmx/addRoleTest?i=3').map(this.extractData);
}
private extractData(res: Response) {
return res.text() ? res.json() : {};
}
app.component.ts
this.dataService.insertappFormData().subscribe((response) => console.log(response));
console output
When I'm trying to assign a variable to response value I'm getting 'undefined' error.
myvar:any;
this.dataService.insertappFormData().subscribe(response => this.myvar = response);
console.log(this.myvar);
I have already go through the below discussions.
Solution-1 ,
Solution-2
But I couldn't solve it.
How to solve this problem?
insertappFormData() returns an observable object which is async. It is executed once you invoke subscribe on it and you should print it out inside subscribe() as:
this.dataService.insertappFormData()
.subscribe(response => {
this.myvar = response;
console.log(this.myvar);
});
Because your console.log(this.myvar); is outside of subscribe.
Change to this:
this.dataService.insertappFormData().subscribe(response => {
this.myvar = response;
console.log(this.myvar);
});
Note: subscribe is an asynchrone function.