Vradhit – 16-20 Feb 4

How to convert async settime out to synchronous
UU
Unknown User804d ago
S
ScriptyChris804d ago
in a dirty way you can use while (true) with date diffing to stop the loop but the question is: why do you need synchronous waiting?
V
Vradhit804d ago
No I mean there was console.log('first') after that setTimeout(console.log('hi') , 0) Question is how to make settimeout console to display first followed by first console?
S
ScriptyChris804d ago
you would like to await it
await new Promise(resolve => {
setTimeout(() => {
console.log('hi');
resolve();
}, 0)
});
console.log('first');
await new Promise(resolve => {
setTimeout(() => {
console.log('hi');
resolve();
}, 0)
});
console.log('first');
or .then() the promise instead of awaiting it !mdn await
UU
Unknown User804d ago
S
ScriptyChris804d ago
!mdn Promise.prototype.then
S
ScriptyChris804d ago
By the way, your question indicates that you are new to event loop (or asynchrony at all) inside JS. So i'd recommend you to get familiar with it: https://www.youtube.com/watch?v=8aGhZQkoFbQ https://javascript.info/async
JSConf
YouTube
What the heck is the event loop anyway? | Philip Roberts | JSConf EU
JavaScript programmers like to use words like, “event-loop”, “non-blocking”, “callback”, “asynchronous”, “single-threaded” and “concurrency”. We say things like “don’t block the event loop”, “make sure your code runs at 60 frames-per-second”, “well of course, it won’t work, that function is an asynchronous callback!” If you’re anything like me...
V
Vradhit804d ago
When we use await So the output is console.log('hi') console.log ('first') Thanks u @ScriptyChris
S
ScriptyChris804d ago
though remember that await may only be used inside async function or at the top level of module file (or in console)
V
Vradhit803d ago
Ok thank u very much
UU
Unknown User803d ago