N
N
Neckvik2019-05-05 22:17:17
Node.js
Neckvik, 2019-05-05 22:17:17

Node js async when calling a function, how?

Help me to understand.
I don't understand a little how Node js can make a function asynchronous?
As far as I understand, it can be done through setImmediate or setTimeout, are there any other options?
setTimeout(0) can be used or is it bad practice ? what is generally better to use?
How can I tell if the function I'm calling is synchronous or asynchronous?
And correctly, I understand that promises do not affect asynchrony in any way, they only help to streamline what will be called for what? Or does what we throw into the promise get into the queue as a new function?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-05-05
@rockon404

I don't understand a little how Node js can make a function asynchronous?

Option 1:
const asyncFn = () => new Promise((resolve, reject) => {
  // do some async call and resolve or reject
});

Example:
const delay = duration => new Promise(res => setTimeout(res, duration));

delay(200).then(() => {
  // do something after delay
});

Option 2:
const asyncFn = async () => {
  // do something with awaiting async call result or not
  // and return result or not
});

Example:
const getSomeData = async () => {
  const result = await someAsyncCall();
  return someOtherAsyncCall(result);
};

Option 3:
const asyncFn = cb => {
  // do some async call and call cb
}

Example:
const delay = (duration, cb) => setTimeout(cb, duration));

delay(200, () => {
  // do something after delay
});

In all cases, you will have to use some built-in asynchronous call, timer, or third-party library in your code.
Typically, such a function returns a Promise or takes a callback.
Read:
Asynchronous Programming Techniques
Understanding Asynchronous Programming

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question