It is a current snapshot of where the JavaScript engine is in our code
This is a JavaScript engine. vroom.
The Event Loop is how the runtime environment tells the engine which block of code to run at what time
Until ES6 there wasn't really a built-in way to execute JavaScript asynchronously
Engine from the previous slide
console.log('Hi');
setTimeout(function cb1()
{
console.log('cb1');
}, 5000);
console.log('Bye');
There is now something called the Job Queue! This is like a priority Event Loop queue.
At their most basic, promises are a bit like event listeners except:
The purpose of async/await is to simplify working with promises
function getNumber1() {
return Promise.resolve('374');
}
// This function does the same as getNumber1
async function getNumber2() {
return 374;
}
function f1() {
return Promise.reject('Some error');
}
async function f2() {
throw 'Some error';
}
await tells the async function which values to wait for
const asyncFun = async function(req, res) {
const data = await axios.get('some url goes here');
res.status(200).send(data)
}
module.exports = {
getStuffAsync: async (req, res) => {
const db = req.app.get("db");
try {
const data = await db.get_my_data();
res.status(200).send(data);
} catch (error) {
res.status(500).send(error);
}
},
getStuffThen: (req, res) => {
const db = req.app.get("db");
db.get_my_data()
.then((data) => {
res.status(200).send(data);
})
.catch((err) => {
res.status(500).send(err);
});
},
};