Search code examples
node.jsasynchronousconcurrencypromisebluebird

How to create concurrent functions call using bluebird promises?


I'm need to organize concurrent race-process of functions Func1 an Func2 and resolve main when the fastest function will be resolved.

const Promise = require('bluebird')

const Func1 = require('./functions/func1')
const Func2 = require('./functions/func2')

let functions = [
    Func1(25),
    Func2(40)
]

Promise.any(functions).spread(response => {
    console.log(response)
})

And both functions looks like

const Promise = require('bluebird')

module.exports = function(data) {
    return new Promise((resolve, reject) => {
        let sum = 0

        // SOME SLOW OPERATION FOR TEST
        for (var i = 1; i <= 1000000000; i++) {
            sum += i * data
        }

        resolve(sum)
    })
}

But with this code, functions run synchronously. And I want them to process concurrent in Promise.any section. How should I rewrite my code to do this? I was trying to wrap functions in process.nextTick, but this hint not working too.


Solution

  • Promises do NOT take synchronous operations and make them into operations that can be run in parallel. That is not what they do nor something they can do. Instead, promises are used to manage or coordinate operations that already by themselves are capable of running in the background while other Javascript is executing. Things like this would be asynchronous file I/O, networking operations, timers, etc...

    Javascript in node.js is single threaded. Unless you start some other process or call some add-on that uses threads/processes via native code, you simply can't run two synchronous operations at the same time in node.js. It is simply not designed to do that yet.

    The usual way to get concurrent execution of multiple synchronous activities in node.js is to run more than one node.js process. When doing that, each node.js process can run independently, can engage multiple CPUs and can truly execute different synchronous operations concurrently. This can be done either with clustering or with some sort of work queue that a group of node.js processes are pulling jobs from or can be done in any number of custom ways by starting other processes.