28

Just a quick question of clarifications: is JavaScript Promise asynchronous? I've been reading a lot of posts on Promise and async programming (namely ajax requests). If Promise is not async, how do we make it so?

For example, I have a function to wrap a function f with argument array args inside a Promise. Nothing about f inherently is async.

function getPromise(f, args) {
 return new Promise(function(resolve, reject) {
  var result = f.apply(undefined, args);
  resolve(result);
 });
}

To make this async, I read some SO posts and decided that the setTimeout is what a lot of people were recommending to make code non-blocking.

function getPromise(f, args) {
 return new Promise(function(resolve, reject) {
  setTimeout(function() { 
   var r = f.apply(undefined, args);
   resolve(r);
  }, 0);
 });
}

Would this approach with setTimeout work to make code non-blocking inside a Promise?

(Note that I am not relying on any third-party Promise API, just what is supported by the browsers).

Jane Wayne
  • 8,205
  • 17
  • 75
  • 120

4 Answers4

40

I think you are working under a misunderstanding. JavaScript code is always* blocking; that is because it runs on a single thread. The advantages of the asynchronous style of coding in Javascript is that external operations like I/O do not require blocking that thread. The callback that processes the response from the I/O is still blocking though and no other JavaScript can run concurrently.

* Unless you consider running multiple processes (or WebWorkers in a browser context).

Now for your specific questions:

Just a quick question of clarifications: is JavaScript Promise asynchronous?

No, the callback passed into the Promise constructor is executed immediately and synchronously, though it is definitely possible to start an asynchronous task, such as a timeout or writing to a file and wait until that asynchronous task has completed before resolving the promise; in fact that is the primary use-case of promises.

Would this approach with setTimeout work to make code non-blocking inside a Promise?

No, all it does is change the order of execution. The rest of your script will execute until completion and then when there is nothing more for it to do the callback for setTimeout will be executed.

For clarification:

    console.log( 'a' );
    
    new Promise( function ( ) {
        console.log( 'b' );
        setTimeout( function ( ) {
            console.log( 'D' );
        }, 0 );
    } );

    // Other synchronous stuff, that possibly takes a very long time to process
    
    console.log( 'c' );

The above program deterministically prints:

a
b
c
D

That is because the callback for the setTimeout won't execute until the main thread has nothing left to do (after logging 'c').

logi-kal
  • 7,107
  • 6
  • 31
  • 43
Paul
  • 139,544
  • 27
  • 275
  • 264
  • I understand a little better now. I suppose (unless I bend over backwards and get to know WebWorkers), using `Promise` won't make my code non-blocking or aysnc. Basically, I will just continue to use `Promise` because at least now I don't have nested callback handling. Thanks. – Jane Wayne Apr 13 '16 at 05:09
  • 11
    I know this answer was written a while ago, but I'm curious if anyone has any references for this? According to MDN, Promises are asynchronous: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise. – Chris Paton Jan 24 '19 at 12:19
  • 2
    I too am trying to figure out, whether a Promise is asynchronous or synchronous. Looking at - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises 'Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.' I understand that promise itself is synchronous, however, it is most generally used in conjunction with asyn functions. Hence, it is said - 'A Promise is an object representing the eventual completion or failure of an asynchronous operation' Examples there include both async and normal functions. – Sachin Ramdhan Boob May 16 '20 at 20:58
  • If Promise is not async, then how come it is allows to use the await keyword - example: `await new Promise...` ? – variable Feb 18 '22 at 11:03
  • @variable because Promise returns an async function in the end. – Baris Senyerli Sep 11 '22 at 12:38
  • 2
    @ChrisPaton I think MDN has been sloppy in describing the behavior of Promises: `"Note that promises are guaranteed to be asynchronous. "` What it should say is "Note that resolving promises are guaranteed to be asynchronous." Just like in the answer, [the `executor` of the constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#syntax) is invoked synchronously. – funct7 Dec 21 '22 at 01:18
  • Also, wondering "whether a Promise is asynchronous" is pointless as it has no meaning. Blocks of codes are run asynchronously. A class or an instance of a class cannot be asynchronous. It's like wondering whether "Jane is a prime number." People tend to use the expression "X is asynchronous" or "asynchronous X", but as far as I'm concerned, the concept of asynchrony cannot be applied to types or instances just like the concept of a prime number cannot be applied to people. – funct7 Dec 21 '22 at 01:22
2

I know this is 7 years old question, but:

Answer:

  • The Promise block is synchronous
  • The Promise callback blocks (resolve, reject) are synchronous
  • The callback call (not the block itself) can be asynchronous if the Promise block uses a setTimeout block

So, to answer the direct question that Jane Wayne was doing, yes, using the setTimeout block will make the Promise block non-blocking.

Explanation:

Javascript is synchronous, it has just 1 thread. The Javascript engine uses a stack (Call Stack) to execute all the stuff (LIFO).

Side to side, you have the Web APIs, that are part of the Browser. There, for example, you can find setTimeout as part of the Window object.

The communication between both worlds is done by using 2 queues (Microtask and Macrotask queues, that are FIFO) managed by the Event Loop, that it is a process that runs constantly.

Event Loop, Microtask and Macrotask queues

The execution goes like:

  • Execute all the script using the Call Stack
  • The Event Loop checks all the time if the Call Stack is empty
  • If the Event Loop finds that the Call Stack is empty, then starts passing callbacks from the Microtask queue, if any, to the Call Stack
  • Once the Microtask queue is empty, the Event Loop does the same for the Macrotask queue

So, getting into the Promise world.

  • The Promise block is executed synchronous
  • Inside the Promise block, you can have something that it is executed outside the Javascript engine (a setTimeout block, for example), that is what we call asynchronous, because it runs outside the Javascript thread.
  • The execution of the callbacks (resolve and reject) of the Promise is what you can consider asynchronous, but the block itself it is executed synchronous

So, if inside the Promise block you do not have any asynchronous block, the Promise will block your execution. And, if in the callback part you do not have any asynchronous block, the Promise will block your execution.

Example:

console.log(`Start of file`)

const fourSeconds = 4000

// This will not block the execution
// This will go to the Macrotask queue
// Microtask queue has preference over it, so all the Promises not using setTimeout
setTimeout(() => {
    console.log(`Callback 1`)
})

// This will block the execution because the Promise block is synchronous
// But the result will be executed after all the Call Stack
// This will be the first Microtask printed
new Promise((resolve, reject) => {
    let start = Date.now()
    while (Date.now() - start <= fourSeconds) { }
    resolve(`Promise block resolved`)
}).then(result => console.log(result))

// This will not block the execution
// This will go into the Macrotask queue because of setTimeout
// Will block all the Macrotasks queued after it
// In this case will block the Macrotask "Callback 2" printing
new Promise((resolve, reject) => {
    setTimeout(() => resolve(`Promise callback block resolved`))
}).then(result => {
    let start = Date.now()
    while (Date.now() - start <= fourSeconds) { }
    console.log(result)
})

// This will not block the execution
// This will go to the Macrotask queue
// Microtask queue has preference over it
// Also the previous Macrotasks has preference over it, so this will be the last thing to be executed
setTimeout(() => {
    console.log(`Callback 2`)
})

// This will not block the execution
// It will go to the Microtask queue having preference over the setTimeout
// Also the previous Microtasks has preference over it
Promise.resolve(`Simply resolved`).then(result => console.log(result))

console.log(`End of file`)

/*

Output:
 
Start of file
[... execution blocked 4 seconds ...]
End of file
Promise block resolved
Simply resolved
Callback 1
[... execution blocked 4 seconds ...]
Promise callback block resolved
Callback 2

*/
Siziksu
  • 21
  • 4
1

const p = new Promise((resolve, reject) => {
  if (1 + 1 === 2) {
    resolve("A");
  } else {
    reject("B");
  }
});

p.then((name) => console.log(name)).catch((name) => console.log(name));
console.log("hello world");

Promise doesn't block the next lines while it's in pending state. So, it works asynchronously.

Amit Kumar
  • 43
  • 2
  • 7
0

Your MDN reference was helpful. Thx. If you run this, you should see asynchronous output.

================================================================ asynchronous using "Promise"

const log = console.log;

//---------------------------------------

class PromiseLab {

    play_promise_chain(start) {
        //"then" returns a promise, so we can chain
        const promise = new Promise((resolve, reject) => {      
            resolve(start);
        });     
        promise.then((start) => {
            log(`Value: "${start}" -- adding one`);
            return start + 1;
        }).then((start) => {
            log(`Value: "${start}" -- adding two`);
            return start + 2;
        }).then((start) => {
            log(`Value: "${start}" -- adding three`);
            return start + 3;
        }).catch((error) => {
            if (error) log(error);
        });             
    }
        
}

//---------------------------------------

const lab = new PromiseLab();
lab.play_promise_chain(100);
lab.play_promise_chain(200);

Output should be asynchronous something like:

Value: "100" -- adding one
Value: "200" -- adding one
Value: "101" -- adding two
Value: "201" -- adding two
Value: "103" -- adding three
Value: "203" -- adding three

================================================================ Synchronous using "MyPromise" (e.g. basic js code)

const log = console.log;

//---------------------------------------

class MyPromise {
    
    value(value) { this.value = value; }
    
    error(err) { this.error = err; }
    
    constructor(twoArgFct) {
        twoArgFct(
            aValue => this.value(aValue),
            anError => this.error(anError));    
    }
    
    then(resultHandler) { 
        const result = resultHandler(this.value);
        return new MyPromise((resolve, reject) => {     
            resolve(result);
        });
    }
    
    catch(errorHandler) { 
        errorHandler(this.error());
    }
    
}

//--------------------------------------
    
class MyPromiseLab {

    play_promise_chain(start) {
        //"then" returns a promise, so we can chain
        const promise = new MyPromise((resolve, reject) => {        
            resolve(start);
        });     
        promise.then((start) => {
            log(`Value: "${start}" -- adding one`);
            return start + 1;
        }).then((start) => {
            log(`Value: "${start}" -- adding two`);
            return start + 2;
        }).then((start) => {
            log(`Value: "${start}" -- adding three`);
            return start + 3;
        }).catch((error) => {
            if (error) log(error);
        });             
    }
        
}

//---------------------------------------

const lab = new MyPromiseLab();
lab.play_promise_chain(100);
lab.play_promise_chain(200);

Output should be synchronous:

Value: "100" -- adding one
Value: "101" -- adding two
Value: "103" -- adding three
Value: "200" -- adding one
Value: "201" -- adding two
Value: "203" -- adding three