This question already has answers here:
Async/Await Class Constructor
(20 answers)
Can async/await be used in constructors?
(4 answers)
Closed 3 years ago.
The keyword await makes JavaScript wait until that promise settles and returns its result.
I noticed its possible to await a function
var neonlight = await neon();
Is it possible to await a class?
Example
var neonlight = await new Neon(neon_gas);
Technically .. Yes, If the constructor returns a Promise and as long as the await is inside an async function, here's an example ( might not be the best, actually it's a bad practice to have a constructor function return a Promise , but it's just to get this to work ):
class Test {
constructor() {
return new Promise((res, rej) => {
this.getData().then(({userId, title}) => {
this.userId = userId;
this.title = title;
res(this);
});
});
}
getData(){
return fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
}
greet(){
console.log('hello');
}
}
(async() => {
const x = await new Test();
console.log(x.userId, ' : ', x.title);
})();
Related
This question already has answers here:
How can I access the value of a promise?
(14 answers)
Async function returning promise, instead of value
(3 answers)
Closed 9 months ago.
I decided to create a special service aka ES6 class with needed functions to get data from API and then in index.js I could create an instance of the class and work with it. Unfortunately, when I try it, it always returns
Promise {<pending>}
and I don't really know what to do.
nytService.js:
export default class NYTService {
urlBase = "https://api.nytimes.com/svc/topstories/v2/";
category = "world";
apikey = *my api key* ;
async getNews(category = this.category) {
let url = `${this.urlBase}${category}.json?api-key=${this.apikey}`;
let res = await fetch(url)
let data = await res.json();
return data;
}
}
index.js:
import NYTService from "../services/nytService.js";
let nytService = new NYTService();
async function getNewsFinally() {
let res = await nytService.getNews();
return res;
}
console.log(getNewsFinally());
I did tried different things with the getNewsFinally function, did various .then chains, nothing helped
See if this tells you why:
async getNews(category = this.category) {
let url = `${this.urlBase}${category}.json?api-key=${this.apikey}`;
try {
let res = await fetch(url)
if (!res.ok) {
return res.statusText;
}
return await res.json();
} catch(err) {
console.error(err);
throw new Error(err);
}
}
This question already has answers here:
Why is my infinite loop blocking when it is in an async function? [duplicate]
(2 answers)
Closed 1 year ago.
I have a function called on a submit form
async solve(e){
const waiter = (args) => new Promise((resolve, reject) => {
resolve(this.CalculateValues(args))
})
e.preventDefault();
let V=this.state.fields;
let B =await waiter(V);
this.setState({
BrokerFees:B,
SolveState:"Solve",
});
}
as you can see in the code I have a function that returns Promise i am using await keyword inside async function still my UI freezes.
Please let me know if I am doing something wrong
I think you should use async here :
solve(e){
const waiter = async (args) => new Promise((resolve, reject) => {
resolve(this.CalculateValues(args))
})
e.preventDefault();
let V=this.state.fields;
let B =await waiter(V);
this.setState({
BrokerFees:B,
SolveState:"Solve",
});
}
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:
When should I use a return statement in ES6 arrow functions
(6 answers)
How to return many Promises and wait for them all before doing other stuff
(6 answers)
Closed 2 years ago.
Why protocols.usd is always returning 0?
I try making a dummy promise function to test it and it's working properly but it's not working with the await function.
async function addPrices() {
const balances = await getBalances();
await Promise.all(balances.map(protocols => {
protocols.usd = 0;
protocols.balances.map(balance => {
if (balance.underlying) {
balance.underlying.map(async token => {
let price = await getPrice(token.address);
protocols.usd += price.market_data.current_price.usd;
});
}
});
}));
return balances;
}
This question already has answers here:
Difference between `return await promise` and `return promise`
(7 answers)
Closed 5 years ago.
const displaySymbols = async (symbols) => {
const sym = await Promise.all(symbols.map(s => {
// createEl return a promise
return createEl(s)
}))
return sym
}
const displaySymbols = async (symbols) => {
const sym = await Promise.all(symbols.map(async s => {
return await createEl(s)
}))
return sym
}
The results are same, without Promise.all, sym would be always a promise array, no matter createEl is await-ed or not, then is it necessary to use async function as map method?
P.S. The code is just a demo.
The second one is superflous. Its like:
Promise.resolve( new Promise() )