Let's go over some weird phenomena here:
const init = async () => {
And
await server.start();
These are fancy new ECMAScript 2017 features.
The server.start()
is what we call a "promise". A promise is a special
function that takes long. Because it takes long, JavaScript will run it
in the background. All while the rest of your function or code can continue to
run.
Below is a simple example of a promise (you don't have to copy it or try it yourself):
function runSomething() {
const promise1 = new Promise(((resolve, reject) => {
setTimeout(() => {
resolve('foo');
}, 300);
}));
promise1.then((value) => {
return console.log(value); // will log "foo"
});
promise1.reject((value) => {
return console.log('it failed:', value)
})
}
If you want to know more about promise you should check out the Mozilla developer for it. But you know what? I suck at this, so have a video instead: https://www.youtube.com/watch?v=DHvZLI7Db8E
The code above is quite extensive, it becomes even worse if you want to write nested promises (like in the JS fetch library):
function fetchSomething() {
return fetch('https://jsonbin.org/remy/blog')
.then((res) => {
return res.json()
.then((json) => {
return json.title
})
})
.reject(res => {
return res.text().then((text => console.log('error: ', res.status, text)))
})
}
See? Things get really messy with returns and then's everywhere. It's much easier to write this instead:
async function fetchSomething() {
const response = await fetch('https://jsonbin.org/remy/blog')
if(response.status !== 200) {
reason = await resonse.text()
raise `error: ${response.status} - ${reason}`
}
result = await respone.json();
return result.title;
}
The "await in our function" stops the rest of the execution of the entire
function all the way up until the async
prefix and waits
until the await step is resolved.