What is the difference b/w the two async/await functions? [duplicate] - javascript

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() )

Related

Javascript is not returning objects as expected [duplicate]

This question already has answers here:
Why do I need to await an async function when it is not supposedly returning a Promise?
(3 answers)
async/await implicitly returns promise?
(5 answers)
async function - await not waiting for promise
(5 answers)
async/await always returns promise
(4 answers)
Closed 5 months ago.
Javascript (or Node.js) is not returning objects as expected.
The following code logs an empty array.
const _sodium = require('libsodium-wrappers');
const sodium = (async () => {
await _sodium.ready;
return _sodium;
})();
console.log(Object.getOwnPropertyNames(sodium));
On the other hand, the following code works as expected.
const _sodium = require('libsodium-wrappers');
(async () => {
await _sodium.ready;
const sodium = _sodium;
console.log(Object.getOwnPropertyNames(sodium));
})();
In the first code snippet, it seems like the sodium object is tied to its lexical environment, which would explain why an empty array is printed. I would be interested in what's going on here (including an explanation of what's going on under the hood). Thanks.
It's not about lexical context.
You just not awaiting for ready in the first example.
First example simplified:
(async() => {
console.log('start')
await new Promise(r => setTimeout(r, 3000))
console.log('finish')
})()
Second example simplified:
console.log('start');
(async() => {
await new Promise(r => setTimeout(r, 3000))
})();
console.log('finish')

How to get variables out from async [duplicate]

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

Map with async not saving element mutation [duplicate]

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;
}

Is it possible to await a class in javascript? [duplicate]

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);
})();

Javascript: Promise.all doesn't seem to be resolving [duplicate]

This question already has answers here:
When should I use a return statement in ES6 arrow functions
(6 answers)
Closed 7 years ago.
I'm trying to map over some RSS feeds using feedparser-promised, but my call to Promise.all() isn't returning anything. (use of var is from my REPL, which doesn't support const or let)
var feedparser = require('feedparser-promised');
var R = require('ramda');
var URLS = ['http://feeds.gawker.com/gizmodo/full',
'http://kotaku.com/vip.xml',
'http://www.medievalhistories.com/feed/'];
var getAllFeeds = (urls) => {
promises = R.map(feedparser.parse, urls);
Promise.all(promises)
.then((itemArrs) => itemArrs)
.catch((err) => {throw new Error(err)});
}
var x = getAllFeeds(URLS);
console.log(x);
x comes back as undefined. If I do a log on promises, it shows as an array of Promises, as expected. What am I missing?
x is undefined because getAllFeeds is a arrow function with statement body that does not explicitly return.
You should return the Promise.all promise and consume the results in then/catch handlers:
var getAllFeeds = (urls) => {
var promises = R.map(feedparser.parse, urls);
return Promise.all(promises)
}
getAllFeeds(URLS)
.then(items => {
console.log(items);
})
.catch(err => {
console.error(err);
})

Categories