To wrap async function calls into a sync function in Node.js or JavaScript, we create a promise from it.
For instance, we write
const asyncOperation = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("hi");
}, 3000);
});
};
const asyncFunction = async () => {
return await asyncOperation();
};
to create a new promise with the Promise
constructor.
We call it with a callback that calls setTime
with a callback that calls resolve
to settle the promise.
Then we call the asyncOperation
function and use await
to get the argument we call resolve
with.