37
loading...
This website collects cookies to deliver better user experience
async/await
is to write async code that behaves similarly to synchronous code, it should execute in the order it was written.Promises
and with async/await
:mkdir node-async-await
npm init -y
to be able to install node packages.cd node-async-await
npm init -y
node-fetch
to make fetch requests.npm install node-fetch
index.js
file.touch index.js
const fetch = require('node-fetch');
async function run() {
const status = await fetch(
'https://jsonplaceholder.typicode.com/todos/1',
)
.then(response => response.json())
.then(res => res);
console.log(status, 'Complete!');
}
run();
touch index-promise.js
const fetch = require('node-fetch');
const data = fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(res => res);
console.log(data, 'Complete!');
async/await
code execution inside the run function is paused without blocking the Node.js process until the Promise chain resolves. Without async/await
the console.log
statement will run before the Promise has resolved. The output in the command line will look like this Promise { <pending> } Complete!
.async/await
with just Promises
the console.log
has to be nested to ensure data was present when using it. With async/await
we don't have to nest the code, so it is more readable.await
will pause execution in the async function, until the awaited Promise resolves. Using await doesn't block the main thread like a synchronous operation would, but pauses execution within the async function where it is used. Once the Promise resolves, execution will begin again where it left off.await
keyword can only be used inside an async
function. It can't be used in the global context and must enclose it in an async function.async/await
comes with a big improvement. When an error or an exception is thrown, it will reference the origin of the error (the function it originated from). Hence, the context of the call is not lost, and the stack trace can be used to debug easier.await
calls in a try/catch
block, instead of using .catch
.const fetch = require('node-fetch');
async function run() {
try {
const status = await fetch(
'https://jsonplaceholder.typicode.com/todos/1',
)
.then(response => response.json())
.then(res => res);
console.log(status, 'Complete!');
} catch (error) {
console.log(error);
}
}
run();
async
function return a Promise
implicitly, so handling errors with a catch handler would also be possible. Though handling errors with a try/catch
block is the common way of doing it, so the error handling is not delegated to the outside of async function.const fetch = require('node-fetch');
async function run() {
const status = await fetch(
'https://jsonplaceholder.typicode.com/todos/1',
)
.then(response => response.json())
.then(res => res);
console.log(status, 'Complete!');
}
run.catch(error => console.log(error));
async/await
is the modern standard for asynchronous code in Node.js