Do Javascript promises block the stack

后端 未结 4 1670
伪装坚强ぢ
伪装坚强ぢ 2020-12-18 01:11

When using Javascript promises, does the event loop get blocked?

My understanding is that using await & async, makes the stack stop until the operation has comp

4条回答
  •  无人及你
    2020-12-18 01:41

    As other mentioned above... Promises are just like an event notification system and async/await is the same as then(). However, be very careful, You can "block" the event loop by executing a blocking operation. Take a look to the following code:

    function blocking_operation_inside_promise(){
        return new Promise ( (res, rej) => {
            while( true ) console.log(' loop inside promise ')
            res();
        })
    }
    
    async function init(){
        let await_forever = await blocking_operation_inside_promise()
    }
    
    init()
    console.log('END')
    

    The END log will never be printed. JS is single threaded and that thread is busy right now. You could say that whole thing is "blocked" by the blocking operation. In this particular case the event loop is not blocked per se, but it wont deliver events to your application because the main thread is busy.

    JS/Node can be a very useful programming language, very efficient when using non-blocking operations (like network operations). But do not use it to execute very intense CPU algorithms. If you are at the browser consider to use Web Workers, if you are at the server side use Worker Threads, Child Processes or a Microservice Architecture.

提交回复
热议问题