JavaScript: Living to see a Promise resolved after a second
Promises in JavaScript are an attempt to escape the need to define a callback on top of a mountain of other callbacks. Too often we find ourselves defining a callback which is a callback to a callback which is called by another callback. However, beginning to use Promises in our code is not straightforward either. To see what that works in practice, we may try to run an example in code, and such an example is presented below.
#!/usr/bin/env node
// index.js
async function returnTrue() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve(true), 1000)
});
let result = await promise;
console.log(result);
return result;
}
async function main() {
let response = returnTrue();
return response;
}
if (require.main === module) {
main();
}
module.exports = { returnTrue };
We await a promise to resolve after a second. This was done thanks to Nick Parsons at this address.
To run that, we execute the file by calling node index.js
.