/    Sign up×
Community /Pin to ProfileBookmark

.js order of execution ?

order of execution ?
Hello ,

Pls , What is the order of execution in code below .

const wait = time => new Promise((resolve) => setTImeout(resolve, time)) ;

wait(3000).then(() => console.log(‘Hello!’)) ;

At what time does 3000 actually get plugged into the variable “time” ?

Thanks

to post a comment
JavaScript

7 Comments(s)

Copy linkTweet thisAlerts:
@rpg2009Mar 07.2021 — I don't know if this helps

``javascript<i>
</i>setTimeout(() =&gt; console.log('third'), 0) // &lt;-- callback queue (macro task queue)

// (resolve) =&gt; resolve('second') &lt;-- microtask queue
const wait = () =&gt; new Promise((resolve) =&gt; resolve('second')) ;

wait().then((message) =&gt; console.log(message)) ;

console.log('first') // Global thread of execution

// Output
// first
// second
// third<i>
</i>
`</CODE>
So with your code, on invocating <STRONG>**wait**</STRONG><br/>
<C>
(resolve) => setTImeout(resolve, time)</C> is put on the microtask queue and presuming there is nothing else on that queue and the callstack is empty is invoked, what within 1ms?

<STRONG>**<EM>_setTimeout_</EM>**</STRONG>, a <EM>_web browser feature_</EM>, sets off a timer of 3 seconds which on completion adds the callback 'resolve' to the callback queue (a.k.a. macro task queue)

given there is no more code in the global thread of execution (nothing below wait(3000)...), the callstack is empty and resolve can be invoked immediately.

edit: Not simple this stuff<br/>
on <STRONG>**<EM>_resolve_</EM>**</STRONG> being invoked the callback setup with <STRONG>**.then(..)**</STRONG> <C>
() => console.log('Hello!')` is added to the microtask queue and on the queue being empty and the callstack being empty can then be invoked

I estimate console.log('Hello') happens around 3002ms possibly?

Note: the order is global code -> microtask queue -> macrotask queue

Something like that : )

edit2: I am missing some of the correct terminology here, fullfillment lists, onfullfillment etc. but that's the jist of it
Copy linkTweet thisAlerts:
@vmars316authorMar 08.2021 — Any chance someone could rewrite this code

into the old (pre-Promise) callback code ?

Then maybe I could understand it .

Thanks
Copy linkTweet thisAlerts:
@vmars316authorMar 08.2021 — like this:

function greeting(name) {<br/>
alert('Hello ' + name);<br/>
}

function processUserInput(callback) {<br/>
var name = prompt('Please enter your name.');<br/>
callback(name);<br/>
}

processUserInput(greeting)
Copy linkTweet thisAlerts:
@vmars316authorMar 08.2021 — @rpg2009#1629016

Thanks ,

I'll study this a while .
Copy linkTweet thisAlerts:
@rpg2009Mar 08.2021 — > @vmars316#1629053 Thanks ,

> I'll study this a while .


To be fair it was unscrambled from my memory, and I don't think it is the clearest of explanations. Diagrams tend to help with these things.
Copy linkTweet thisAlerts:
@rpg2009Mar 09.2021 — > @vmars316#1629052

> ``<i>
&gt; </i>function greeting(name) {
<i>&gt; </i> alert('Hello ' + name);
<i>&gt; </i>}
<i>&gt; </i>
<i>&gt; </i>function processUserInput(callback) {
<i>&gt; </i> var name = prompt('Please enter your name.');
<i>&gt; </i> callback(name);
<i>&gt; </i>}
<i>&gt; </i>
<i>&gt; </i>processUserInput(greeting)
`</CODE></QUOTE>

window.prompt as far as I can tell is synchronous and code blocking. Your setTimeout was probably a better example as it simulates asynchronous procedures.

Just having a play with the two different approaches side by side

<H3>### With callbacks</H3>
<CODE lang="javascript">
`javascript<i>
</i>function greeting(details, callback) {
console.log(
Hello ${details.name})
setTimeout(() =&gt; callback(details), 1000)
}

function age(details, callback) {
console.log(
Your age is ${details.age})
}

function processDetails(details, callback) {
setTimeout(() =&gt; callback(details, age), 2000)
}

processDetails({name: 'Bob', age: 27}, greeting)
// Asynchronous code above
console.log('Still able to do stuff here')<i>
</i>
`</CODE>
<H3>### With promises</H3>
<CODE lang="javascript">
`javascript<i>
</i>function greeting (details) {
console.log(
Hello ${details.name})

return new Promise((resolve) =&gt; {
setTimeout(() =&gt; resolve(details), 1000)
})
}

function age (details) {
console.log(
Your age is ${details.age})
}

function processDetails (details) {
return new Promise((resolve) =&gt; {
setTimeout(() =&gt; resolve(details), 2000)
})
}

processDetails({name: 'Steve', age: 50})
.then(greeting)
.then(age)

console.log('Still able to do stuff here')<i>
</i>
`</CODE>
At first glance the '<STRONG>**<EM>_with promises_</EM>**</STRONG>' version does seem more verbose compared to the callback version. I guess we have to remember we would more than likely be using features that implicitly return promises like <STRONG>**<EM>_response.json()_</EM>**</STRONG>, rather than having to create our own.

The standout to me is that the <STRONG>**<EM>_promise_</EM>**</STRONG> version of <EM>_processDetails_</EM>, unlike the <STRONG>**<EM>_callbacks_</EM>**</STRONG> version, is not tightly coupled to the <EM>_age_</EM> function.

<C>
setTimeout(() => callback(details, age), 2000)`

The callbacks instead are handled by registering them with the **.then** method and the sequence of events is pretty clear — Not so much the '**_with callbacks_**' version.
Copy linkTweet thisAlerts:
@vmars316authorMar 17.2021 — rpg2009 ;

Great example 'with promises' ,

and this comment makes it clear

"The callbacks instead are handled by registering them with the .then method and the sequence of events is pretty clear — Not so much the 'with callbacks' version."

Thank you
×

Success!

Help @vmars316 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...