简体   繁体   中英

How to make Javascript Promise.all fun functions concurrently

From what I understand from Promise.all documentation, it is possible run two or more functions simultaneously and wait until all of them to be completed. So I tried this:

function execute(id, max) {
    console.log('starting ' + id);

    console.time(id);
    var sum = 0;
    for(var i = 0; i < max; i ++) {
        sum += i;
    }
    console.timeEnd(id);
    return sum;
}

console.log("Declaring p1");
var p1 = Promise.resolve(() => execute("p1", 10000));
console.log("Declaring p2");
var p2 = Promise.resolve(() => execute("p2", 100000));

console.log("Calling Promise.all");
console.time("all"); 
Promise.all([p1, p2]).then((values) => console.log("Then: " + values));
console.timeEnd("all");

However, what I got (running in Chrome) was this:

Declaring p1
Declaring p2
Calling Promise.all
all: 0.599ms
Then: () => execute("p1", 10000),() => execute("p2", 100000)

So apparently, not only the functions were not running as well as the then method got them, not the results.

Even if I replace the promises by the original functions calls I had the same result:

function execute(id, max) {
    console.log('starting ' + id);

    console.time(id);
    var sum = 0;
    for(var i = 0; i < max; i ++) {
        sum += i;
    }
    console.timeEnd(id);
    return sum;
}

console.log("Calling Promise.all");
console.time("all");
Promise.all([() => execute("p1", 10000), () => execute("p2", 100000)])
  .then((values) => console.log("Then: " + values));
console.timeEnd("all");

The output was:

Calling Promise.all
all: 0.274ms
Then: () => execute("p1", 10000),() => execute("p2", 100000)

So, I think that I misunderstood the Promise.all usage. How do I execute parallel processing using Promises?

Thanks,

Rafael Afonso

Promise.all takes array of promises and resolves as soon as all are resolved or one of them rejects. But promises are not asynchronous by spec, actually, total opposite is true: Promise executor is executed immediately . So if all of your executors are synchronous, then your promise chain is synchronous.

Maybe that helps a little bit to understand how it works:

function execute(id, max) {
    console.log('starting ' + id);

    console.time(id);
    var sum = 0;
    for(var i = 0; i < max; i ++) {
        sum += i;
    }
    console.timeEnd(id);
    return sum;
}

console.log("Declaring p1");
var p1 = Promise.resolve(execute(1, 10));

console.log("Declaring p2");
var p2 = new Promise((resolve, reject) => {
  console.log('setting timeout..');
  setTimeout(() => resolve(execute(2,10)), 2000);
})

console.log("Calling Promise.all");
console.time("all");
console.time('results');
Promise.all([p1,p2])
  .then((results) => { 
      console.log('all results', results); 
      console.timeEnd('results'); 
  })
  .catch(console.error.bind(console));

console.timeEnd("all"); // Promise.all returns immediately

And thats the output:

Declaring p1
starting 1
1: 0.016ms
Declaring p2
setting timeout..
Calling Promise.all
all: 0.097ms
starting 2
2: 0.002ms
all results [45, 45]
results: 2001.144ms

Usually, Promises are used when calling some asynchronous API. But if you really want to run your own javascript asyncronously, you need to use Web Workers or something, depending on your platform.

Edit: Some quick googling about Web Workers and Promises, there is good looking library promise-worker . By good looking I mean, 100 % coverage and automated browser tests. Probably worth of inspecting, or even installing, if you want to go that route.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM