cytrinox
cytrinox

Reputation: 1946

Nodejs did not execute a promise function asynchronous

I've written a small example js to learn how to work with Promises. I expected that the script starts and immediately outputs "start" and few seconds later "45". But insead, the script starts without any output and before exit, both lines are printed. Have I misunderstood how Promises working or is there a buffering issue?

;(function(main, undefined) {
        "use strict";

        main.test = function() {
                return new Promise(function(resolve, reject) {
                        for(var i = 0; i < 999999999; ++i);
                        resolve(45);
                });
        };

})(global);

global.test().then(function(r) {
        console.log(r);
});


console.log("start");

$ node -v v0.12.6

Upvotes: 1

Views: 164

Answers (2)

mikefrey
mikefrey

Reputation: 4681

Wrapping code in a promise does not make it execute asynchronously. It makes working with asynchronous code easier.

In your example, your loop executes synchronously. Here is your example using setTimeout, which executes asynchronously, instead of a for loop.

;(function(main, undefined) {
        "use strict";

        main.test = function() {
                return new Promise(function(resolve, reject) {
                        setTimeout(function() { resolve(45); }, 5000)
                        console.log(44);
                });
        };

})(global);

global.test().then(function(r) {
        console.log(r);
});


console.log("start");

In this example, the output will be:

start
44
45

Upvotes: 6

Peter Lyons
Peter Lyons

Reputation: 145994

Yes, you have a slight misconception. Promises can do or start work on the same event loop tick when they are created, which is what your sample does. Then they eventually yield the event loop and their result is guaranteed to not resolve nor reject on the starting tick, always after.

Since typically promises are used for async IO, you don't normally notice the time spent preparing the work in the same tick. For example, constructing a SQL query which then gets sent to a DB and when that is done, resolve the promise. However, in an extreme case, if you had an enormous, complex SQL query to build via synchronous string manipulation, that would occupy the initial tick until it was finally sent over the network to the DB, then code would proceed with additional ticks, and eventually when the response arrived from the DB, the promise would resolve.

Upvotes: 0

Related Questions