F
F
fon_harry2018-09-08 21:43:08
JavaScript
fon_harry, 2018-09-08 21:43:08

How much is the execution time of two promises sequentially equivalent to the parallel execution time?

I want to execute two promises sequentially, but the result of the time is the same as with parallel execution. What am I doing wrong?

const getA = new Promise((resolve, reject) => {
    console.time('getA');
    setTimeout(() => {
        console.timeEnd('getA');
        resolve(4)
    }, 6000)
});

const getB = new Promise((resolve, reject) => {
    console.time('getB');
    setTimeout(() => {
        console.timeEnd('getB');
        resolve(2)
    }, 2000)
});


console.time('get sum');
getA.then(a => {
    getB.then(b => {
        console.log(`result: ${a + b}`);
        console.timeEnd('get sum');
        })
    });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-09-08
@fon_harry

time result as in parallel execution

And why how? They are running in parallel. To be consistent - the second must be created in the then of the first.
UPD. Taken from the comments:
You can make getA and getB functions that return promises - then it will be as you want:
const getA = () => new Promise((resolve, reject) => {
    console.time('getA');
    setTimeout(() => {
        console.timeEnd('getA');
        resolve(4)
    }, 6000)
});

const getB = () => new Promise((resolve, reject) => {
    console.time('getB');
    setTimeout(() => {
        console.timeEnd('getB');
        resolve(2)
    }, 2000)
});


console.time('get sum');
getA().then(a => {
    getB().then(b => {
        console.log(`result: ${a + b}`);
        console.timeEnd('get sum');
        })
    });

UPD. Cabac_B is perplexed in the comments about "execute in parallel":
Well, not literally in parallel, and not literally executed - see the code in question. It meant that both promises are waiting for their resolution at the same time.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question