how to use async await correctly [duplicate] - javascript

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

Related

Problems with async/await and promise using setTimeout [duplicate]

This question already has answers here:
Combination of async function + await + setTimeout
(17 answers)
Closed 9 months ago.
I've the following code that should have to works for a slider:
let timeOut, timeOut2;
over = 1;
let back = 0;
setInterval(change2, 8000);
async function change2() {
innerFront = slides[over];
innerBack = slides[back];
await setTimeout(change, 8000);
innerFront.querySelectorAll('figure')[0].classList.remove('isActive');
innerFront.classList.remove('slideshow__inner--front');
innerBack.querySelectorAll('figure')[0].classList.remove('isActive');
innerBack.classList.remove('slideshow__inner--back');
over -= 1;
if (over < 0) over = slides.lenght;
back = over - 1;
if (back < 0) back = slides.lenght;
slides[over].classList.add('slideshow__inner--front');
slides[back].classList.add('slideshow__inner--back');
}
function change() {
return new Promise(function(resolve, reject) {
innerFront.querySelectorAll('figure')[0].classList.add('isActive');
timeOut2 = setTimeout(()=> {
innerBack.querySelectorAll('figure')[0].classList.add('isActive');
}, 1000);
resolve();
});
}
My problem consists in the fact that the 'change' function seems not to be performed despite the Await for Promise. In fact, the subsequent instructions are immediately performed, and obviously this generate errors.
I still have doubts about the promises, which I am studying, and here I think there can be something conceptual.
Does anyone have the patience to explain to me where I'm wrong?
There's a typo inside of change2() you wrote lenght instead of length twice.

How to make a function wait until its recursive instances are completed too? - Javascript [duplicate]

This question already has answers here:
Combination of async function + await + setTimeout
(17 answers)
How to make a promise from setTimeout
(8 answers)
Closed 10 months ago.
I have two functions in JS, one calls another, but the first one tries again itself after one second if a condition goes false. The problem is, I want the second function to await until this recursive instances are done too.
Here's what I have until now:
async function firstFunction(){
if(SomeCondition){
//do something
}
else{
//do something
setTimeout(() => {
firstFunction();
}, 1000);
//Tries again in 1 second
}
}
async function secondFunction(){
await firstFunction() //waiting firstFunction and its instances to finish
}
Can't figure out how to solve this, any idea?
Since you've made firstFunction async - use Promises to do what you need
async function firstFunction() {
if (SomeCondition) {
//do something
} else {
//do something
await new Promise(r => setTimeout(r, 1000))
await firstFunction();
}
}
async function secondFunction() {
await firstFunction() //waiting firstFunction and its instances to finish
}

How do I change below callback code to async/await version? [duplicate]

This question already has answers here:
How do I convert an existing callback API to promises?
(24 answers)
Closed 1 year ago.
I'm trying to convert this callback to async/await but seems I can't figure out how to do it.
function getTotalUsersCount(callback) {
User.count({}).exec((err, count) => {
if (err) {
return callback(null, 0);
}
return callback(null, count);
});
},
Also I want to change the
User.count({}).exec((err, count)
to this
const count = await User.count();
If you are using Mongoose then it should work.
function getTotalUsersCount() {
return User.count({})
};
async function test() {
const result = await getTotalUsersCount();
}
Almost every Mongoosecall returns promise if you don't pass the callback, so you can use async/await syntax in any async function.
If you want you can wrap the function in a promise manually.
function getTotalUsersCount() {
return new Promise((res, rej) => {
User.count({}).exec((err, count) => {
if (err) {
return rej(err);
}
return res(count)
});
});
};
And you still should be able to call this funciton in the same way as I shoved above in the test function.

Return a value from a setTimeout [duplicate]

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! */
}

Get return value from setTimeout [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
The community is reviewing whether to reopen this question as of 9 days ago.
I just want to get the return value from setTimeout but what I get is a whole text format of the function?
function x () {
setTimeout(y = function () {
return 'done';
}, 1000);
return y;
}
console.log(x());
You need to use Promises for this. They are available in ES6 but can be polyfilled quite easily:
function x() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('done!');
});
});
}
x().then((done) => {
console.log(done); // --> 'done!'
});
With async/await in ES2017 it becomes nicer if inside an async function:
async function() {
const result = await x();
console.log(result); // --> 'done!';
}
You can't get a return value from the function you pass to setTimeout.
The function that called setTimeout (x in your example) will finish executing and return before the function you pass to setTimeout is even called.
Whatever you want to do with the value you get, you need to do it from the function you pass to setTimeout.
In your example, that would be written as:
function x () {
setTimeout(function () {
console.log("done");
}, 1000);
}
x();
Better to take a callback for function x and whatever task you want to perform after that timeout send in that callback.
function x (callback) {
setTimeout(function () {
callback("done");
}, 1000);
}
x(console.log.bind(console)); //this is special case of console.log
x(alert)
You can use a combination of Promise and setTimeOut like the example below
let f1 = function(){
return new Promise(async function(res,err){
let x=0;
let p = new Promise(function(res,err){
setTimeout(function(){
x= 1;
res(x);
},2000)
})
p.then(function(x){
console.log(x);
res(x);
})
});
}
I think you want have flag to know event occured or no. setTimeout not return a value. you can use a variable to detect event occured or no
var y="notdone";
setTimeout(function () {
y="done";
}, 1000);
You can access variable y after timeout occured to know done or not

Categories

Resources