We have to choose async waiting for a promise in Javascript

I know that async await- this is new Promisein the city, and this is a new way to write asynchronous code, and I also know that

We do not need to write .then, create an anonymous function to process the response

Async/await finally allows you to handle both synchronous and asynchronous errors with the same design, the old old try / catch

The error column returned from the chain Promisegives no idea where the error occurred. However, the async / await error stack points to a function containing the error

And SO ON ...

but here I made a simple label https://repl.it/repls/FormalAbandonedChimpanzee

In the benchmark, I missed 2 cycles 1 million times. In the first loop, I call a function that returns 1 in another function, I call a function that throws 1 as an exception.

the time taken by the first loop that calls the function returning 1 is almost half the function that throws 1 as an error.

Which shows that the time spent on throwis almost half the time spent onreturn

node v7.4 linux/amd64

return takes 1.233seconds
1000000
throw takes 2.128seconds
1000000

Verification code below

function f1() {
  return 1;
}

function f2() {
  throw 1;
}

function parseHrtimeToSeconds(hrtime) {
    var seconds = (hrtime[0] + (hrtime[1] / 1e9)).toFixed(3);
    return seconds;
}

var sum = 0;
var start = 0;
var i = 0;

start = process.hrtime();
for (i = 0; i < 1e6; i++) {
  try {
    sum += f1();
  } catch (e) {
    sum += e;
  }
}
var seconds = parseHrtimeToSeconds(process.hrtime(start));
console.log('return takes ' + seconds + 'seconds');
console.log(sum);




sum = 0;
start = process.hrtime();
for (i = 0; i < 1e6; i++) {
  try {
    sum += f2();
  } catch (e) {
    sum += e;
  }
}

seconds = parseHrtimeToSeconds(process.hrtime(start));
console.log('throw takes ' + seconds + 'seconds');
console.log(sum);
+4
source share
2 answers

Your test has nothing to do with performance between async/awaitand raw promises. All I see is that it takes longer to calculate the error. Expected.

, async/await, .then raw promises?

, async/await raw promises, . , , .

- , . Promises polyfill 'd, , , , .


:

, , , .

. :

function error() {
    return new Promise(function(res, rej) {
        res(undefined()); // uh oh
    });
}

error().then(console.log, e => console.log("Uh oh!", e.stack));

, .

+5

, " ".

, async/await vs raw Promise.

async/await - , Promise .

async function foo() {
  const a = await backend.doSomething()
  const b = await backend.doAnotherThing()
  return a + b
}

backend.doAnotherThing() , backend.doSomething() . :

function foo() {
  Promise.all([backend.doSomething(), backend.doAnotherThing()])
    .then(([a, b]) => {
       return a + b
    })
}

.

async/await, . , .

, async/await vs Promise , async/await Promise, .

, .

+3

Source: https://habr.com/ru/post/1689936/


All Articles