Preface#
In actual development, we often encounter situations where we need to perform "delay" operations in asynchronous operations. Usually, we write a util
function similar to the following to handle it.
const delay = (ms: number) => new Promise((r) => setTimeout(r, ms));
This is good, concise, and perfectly fits our needs. However, if your code runs in a pure node
environment, there is a new alternative solution to consider.
Using the node Timers Promises API#
Why not try the setTimeout
function provided by the Timers Promises API supported by node
starting from v15.0.0? It returns a Promise
that behaves similarly to the delay function we just mentioned, while also supporting more usage.
import { setTimeout } from 'node:timers/promises'
const sayHi = async () => {
console.log('Hi!')
}
const doSomethingAsync = async () => {
console.log('yolo!')
await setTimeout(1000)
await sayHi()
const res = await setTimeout(1000, 'result');
console.log("res is: ", res)
}
doSomethingAsync()
The output of the above code is as follows.
yolo! # Output immediately
Hi! # Output after one second
res is: result # Output after another second
For more details, please refer to the Node.js official documentation.