Return a value from a setTimeout [duplicate] - javascript

This question already has answers here:
how to make Javascript setTimeout returns value in a function
(2 answers)
Javascript return value from setTimeout [duplicate]
(1 answer)
Get return value from setTimeout [duplicate]
(5 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I'm trying to return a value calculated in a setTimout. But it seems like I can't do get this value. I read that to do this I must use promises. Am I obliged to use this like this exemple : https://italonascimento.github.io/applying-a-timeout-to-your-promises/ ?
My code :
renderTeaserBackground = () => {
return setTimeout(function() {
this.setState({ teaserAnimCount: this.state.teaserAnimCount + 1 });
let teaserBackground = teaserBgImg[this.state.teaserAnimCount];
console.log(teaserBackground);
}.bind(this), this.state.teaserAnimDuration * 1000);
return 'teaserBackground';
}
Thanks

You can use a Promise!
ES6 way - Standard Promises:
renderTeaserBackground = () => new Promise(res => {
setTimeout(_ => {
this.setState({teaserAnimCount: this.state.teaserAnimCount + 1});
let teaserBackground = teaserBgImg[this.state.teaserAnimCount]
res(teaserBackground) //Return it here!
}, this.state.teaserAnimDuration * 1000);
})
To use this outside, you can do:
const mainLogic = _ => {
return renderTeaserBackground().then(teaserBackground => {
/* Use teaserBackground as you need! */
})
}
ES7 way - Harmony async/await
const mainLogic = async _ => {
const teaserBackground = await renderTeaserBackground()
/* Use teaserBackground as you need! */
}

Related

how to use async await correctly [duplicate]

This question already has answers here:
How to make a promise from setTimeout
(8 answers)
How to handle multiple async requests?
(2 answers)
Closed 6 months ago.
this is regarding async await and promises. I am not very good at this so I guess i´m missing something. My code is meant to execute the first greetings function which it does. But then only once its done (and only then) it should execute any consecutive functions.
I have tried setting it up in many ways but either the second function doesn't execute or it executes before completion of the first.
Here is my code:
const greetingDivs = [firstDiv, secondDiv, thirdDiv, fourthDiv, fifthDiv]
let y = 0
function greetings() {
if (y != greetingDivs.length) {
setTimeout(() => {
consoleOutput.appendChild(greetingDivs[y])
y++
}, 500)
setTimeout(() => {
greetings()
}, 500)
}
if (y == greetingDivs.length) {
return console.log('Greetings are done!')
}
}
function secondFunction() {
console.log('I have waited')
}
async function consoleOn() {
const result = await greetings()
if (result) {
secondFunction()
}
}
consoleOn()

JavaScript async/await makes 'undefined' [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How do I convert an existing callback API to promises?
(24 answers)
Closed 8 months ago.
I have a problem with a JavaScript function that it has async await. I create this with the goal of learning asynchrony.
// function that just solve an addition
function addition(num1, num2){
let sum = num1 + num2
return sum
}
// I treat this function as an api
function num(value=3){
setTimeout( function (){
let num = value;
return num
}, 3000)
}
// I put an async/await for waiting the response of 'num' function
const Exercise = async() => {
const num2 = await num(2)
console.log(addition(3,num2))
}
Exercise()
The num() function has a behaviour as an API what I've to wait it response, but when I run all of this code the first response is 'undefined' and then 'NaN'. I don't understand why.
Do you know what I'm doing wrong?
Thanks a lot!

javascript wait until variable is set [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 months ago.
Can you make a function wait until a variable is set by another function? This is my example:
function setvar(){
//some process that may take a while
myvar = 'value';
}
const promise1 = new Promise((resolve, reject) => {
resolve(myvar);
});
promise1.then((value) => {
console.log(value);
});
this doesnt seem to work, the function begins even if the variable is not ready. What should I do? I dont want settimeout or setinterval because I dont know exactly how long it is going to take each time.
In the promise you'll need create a loop that would check if variable was set:
var myvar;
function setvar(){
//some process that may take a while
myvar = 'value';
}
const promise1 = new Promise((resolve, reject) => {
const loop = () => myvar !== undefined ? resolve(myvar) : setTimeout(loop)
loop();
});
promise1.then((value) => {
console.log(value);
});
setTimeout(setvar, 2000);

Node JS Promise won't return a value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
The below code is not returning a value back but it console logs out fine. Any ideas how I can set the value of X?
var dbSize = dbo.collection('Items').count()
var x = 0
x = dbSize.then(len => {
return len
})
This is what is being logged 'Promise { }' however if I simply write this:
dbo.collection('Items').count()
var x = 0
dbSize.then(len => {
console.log(len)
})
then It logs out fine.
you can warp your code with an async function and then use await to make your code work like synchronized code
const a = async () =>{
var dbSize = await dbo.collection('Items').count()
console.log(dbSize)
}
a();

How to return async result from a method? [duplicate]

This question already has answers here:
Meteor: Proper use of Meteor.wrapAsync on server
(4 answers)
Closed 6 years ago.
I am trying to return a value from a Meteor.method returned by an async callback function, like so:
Meteor.method('myMethod', () => {
asyncFunction(result => {
// Meteor.method should return this result
});
});
Where should I put the return result; statement?
you can try this:
Meteor.method('myMethod', () => {
return asyncFunction(result => {
// Meteor.method should return this result
return result;
});
});

Categories

Resources