How can I tell if my promise.all is running in parallel?

梦想与她 提交于 2020-01-06 02:49:08

问题


I have the following Promise.all example. I was wondering if it was operating in "parallel" in regards to the lambda.invoke? And how can I test if something is running parallel?

Referenced this thread

function get1(id) {
    return new Promise((resolve, reject) => {
        const params = {
            FunctionName: 'myLambda', // the lambda function we are going to invoke
            InvocationType: 'RequestResponse',
            Payload: { id },
        };

        lambda.invoke(params, (err, data) => {
            if (err) {
                reject(new Error('error'));
            } else {
                const result = JSON.parse(data.Payload);
                resolve(result);
            }
        });
    }).catch(e => Promise.resolve({ error: 'Error has occurred.' }));
}

exports.getDetails = list => Promise.all(list.map(get1))
    .then((response) => {
        return result;
    }).catch((error) => {
        console.log('oops ', error);
    });

回答1:


You could count how many actions are started and haven't finished yet:

  let running = 0;

  // Inside of the promise:
  running++;
  lambda.invoke(params, (err, data) => {
    running--;
    console.log(`lambda.invoked finished, ${running} tasks still running`);
  });

If invoke is synchronous, you get:

  lambda.invoked finished, 0 tasks still running
  lambda.invoked finished, 0 tasks still running
  lambda.invoked finished, 0 tasks still running

If it is asynchronous you get:

  lambda.invoked finished, 2 tasks still running
  lambda.invoked finished, 1 tasks still running
  lambda.invoked finished, 0 tasks still running



回答2:


One way to test would be to baseline how long the call should take, and how long it takes Promise.all to complete. If tasks are executed serially, and each call takes ~1 second, a list of 5 elements it should take ~5 seconds to complete. However, if they are running in parallel, they should take closer to ~1 second (although probably slightly higher due to inherent overhead). Basically, you are checking to see if it completes as quickly as the longest task, or if it completes after the sum of time it takes to complete all tasks.



来源:https://stackoverflow.com/questions/51910097/how-can-i-tell-if-my-promise-all-is-running-in-parallel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!