node js await on code example
Example 1: node js request async await
function doRequest(url) {
return new Promise(function (resolve, reject) {
request(url, function (error, res, body) {
if (!error && res.statusCode == 200) {
resolve(body);
} else {
reject(error);
}
});
});
}
async function main() {
let res = await doRequest(url);
console.log(res);
}
main();
Example 2: await in node js
function square(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(Math.pow(x, 2));
}, 2000);
});
}
async function layer(x)
{
const value = await square(x);
console.log(value);
}
layer(10);