Question: ```
setTimeout(function () {
    console.log('timeout1')
}, 0);

setImmediate(function () {
    console.log('immediate1')
});

new Promise(function (resolve, reject) {
    console.log('promise1');
    resolve()
}).then(function () {
    console.log('then1');
    setTimeout(function () {
        console.log('timeout2')
    }, 0)
});

console.log('global1');

```

when I use node.js to excute these code above many times,I get the different results; some times the result is

> 
> "promise1"-->"global1"-->"then1"-->"timeout1"-->"immediate1"-->"timeout2";
> 
> 
> 

and other times the result is

> 
> "promise1"-->"global1"-->"then1"-->"timeout1"-->"timeout2"-->"immediate1"
> 
> 
> 

is there something wrong?

Answer: 
The first few events with the promise and the synchronous code are normal and probably what you expect. (Code in the promise definition is fired synchronously, which seem surprising at first.) The difference between order of `setTimout()` with 0 delay and `setImmediate()` is is non-deterministic. This is documented here:

[The Node.js Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/)

> 
> For example, if we run the following script which is not within an I/O cycle (i.e. the main module), the order in which the two timers are executed is non-deterministic, as it is bound by the performance of the process:
> 
> 
> 
> ```
> // timeout_vs_immediate.js  
> setTimeout(() => {  
>     console.log('timeout');  
> }, 0);  
> 
> setImmediate(() => {  
>     console.log('immediate');  
> });
> 
> ```
> 
>
In Javascript the execution happens asynchronously, The event loop picks up the commands and runs it. This is as designed as and you can read it [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop) 

If you by chance want a particular order then you can use callbacks, promises or async/await.
If you use Async/Await then you need to specify that particular function as Async and you would be able to control the internal flow of that function in a synchronous way but the function wrt outer program will still run asynchronously.

I hope its not too confusing so let me reiterate, everything is asynchronous but you can make a small part(function) sync which would follow step by step order of execution but wrt the other functions and programs your function can be executed in order thats not fixed.