A
A
Alexey Yarkov2017-03-10 13:47:57
Node.js
Alexey Yarkov, 2017-03-10 13:47:57

How does async/await work in Node?

Code example:

const fs = require('fs');
const keypair = require('keypair');


console.log('Before');

async function generate(bits=2048) {
  let pair = await new Promise((res, rej) => {
    res(keypair({
      bits
    }));
  });
  console.log('Generated');
  fs.writeFileSync('./private.key', pair['private']);
  fs.writeFileSync('./public.key', pair['public']);
}

generate(2048);

console.log('After');

Result:
$ node keypair.js
Before
# Ожидание 2-8 сек
After
Generated

Isn't that how it should be?
$ node keypair.js
Before
After
# Ожидание 2-8 сек
Generated

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nick8, 2017-03-12
@yarkov

No, it shouldn't. Promise immediately returns a resolve with this function, which is executed. In order for it to be the way you want, the keypair function itself must return a promise, which will then be awaited by await.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question