returning first value [object Promise] [duplicate] - javascript

This question already has answers here:
async/await implicitly returns promise?
(5 answers)
Why is my asynchronous function returning Promise { <pending> } instead of a value?
(9 answers)
Async function returning promise, instead of value
(3 answers)
How can I access the value of a promise?
(14 answers)
What are asynchronous functions in JavaScript? What is "async" and "await" in JavaScript?
(2 answers)
Closed 8 months ago.
const wordEl = document.getElementById('word');
let selectedWord = [];
let correctLetters = [];
let apiUrl = 'https://random-word-api.herokuapp.com/word';
async function getData(url) {
let response = await fetch(url);
let data = await response.json();
selectedWord = await data;
}
selectedWord = getData(apiUrl);
async function displayWord() {
wordEl.innerHTML = `
${selectedWord
.toString()
.split('')
.map(
(letter) =>
`
<span class="letter">
${correctLetters.includes(letter) ? letter : ''}
</span>
`
)
.join('')}
`;
}
window.addEventListener('keydown', (e) => {
if (selectedWord.toString().includes(e.key)) {
if (!correctLetters.includes(e.key)) {
correctLetters.push(e.key);
displayWord();
}
}
});
displayWord();
Hello my first value returning [object promise]. After pressing any key value returning what I want.
How can i get normal value before clicking any key? Thank you!

Related

Promise { <pending> } [duplicate]

This question already has answers here:
async/await implicitly returns promise?
(5 answers)
Why is my asynchronous function returning Promise { <pending> } instead of a value?
(9 answers)
Async function returning promise, instead of value
(3 answers)
How can I access the value of a promise?
(14 answers)
What are asynchronous functions in JavaScript? What is "async" and "await" in JavaScript?
(2 answers)
Closed 4 months ago.
static async updatePaidLeave() {
const result = await PaidUnpaidLeaveSchema.find({});
console.log(result, ";;;;;;;");
}
static runCronJob() {
cron.schedule("*/10 * * * * *", async () => {
this.updatePaidLeave();
console.log(this.updatePaidLeave(), "Im running in every 10 seconds.");
});
}
Output // Promise { } Im running in every 10 seconds.
i have tried above code and i want data from PaidUnpaidLeaveSchema
The code requires a couple of fixes. Try this (look at comments):
static async updatePaidLeave() {
const result = await PaidUnpaidLeaveSchema.find({});
console.log(result, ";;;;;;;");
return result // return result
}
static runCronJob() {
cron.schedule("*/10 * * * * *", async () => {
const result = await this.updatePaidLeave(); // await and save result in a variable
console.log(result, "Im running in every 10 seconds."); // log result
});
}

Filtering a list of promises inside useEffect [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How can I access the value of a promise?
(14 answers)
Closed 7 months ago.
I found that it's not straight forward to filter a list of values of promises, so I tried the approach in this question (top answer).
The difference is, i'm using this inside useEffect in React.
My results array is empty outside of the async getData function:
// helper function
async function filter(arr, callback) {
const fail = Symbol();
return (
await Promise.all(arr.map(async (item) => ((await callback(item)) ? item : fail)))
).filter((i) => i !== fail);
}
useEffect(() => {
if (!stateData) {
let results = [];
async function getData() {
const res = await filter(data.slice(0, 5), async (item) => {
const boolRes = await myAsyncFunction(item);
return boolRes;
});
// results has data
results.push(...res);
}
getData();
console.log(results) // is empty, but results inside getData has data
}
}, []);
any idea how I can pull the data out of getData safely?

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

How to use an array which is returned from 1 function in Nodejs? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have 1 function in Nodejs that return a list of recipient:
var recipientList = [];
userService.listUser().then( result => {
var listPSID = result.filter(result => !'279'.includes(result));
recipientList = listPSID.slice();
console.log(recipientList);
});
Now I want to access that list OUTSIDE the function, something likes:
console.log(recipientList[0]);
How can I do that? Thank you all.
If you're using Promises, you cannot access it outside the function. If you use async / await instead, it should work.
async function getList(){
let result = await userService.listUser();
var listPSID = result.filter(result => !'279'.includes(result));
recipientList = listPSID.slice();
console.log(recipientList[0]);
}

Categories