JavaScript is single-threaded and runs in the same thread as the UI. So all JavaScript code will block the UI. As mentioned by others web workers can be used to run code in other threads, but they have limitations.
The difference between async functions and regular ones is that they return a promise. Using a callback you can then defer the execution of code, that handles the result of a function invocation and thereby allowing the UI to do some work. The following three examples have the same effect:
async function foo() {
console.log("hi");
return 1;
}
foo().then(result => console.log(result))
console.log("lo");
function foo() {
console.log("hi");
return 1;
}
Promise.resolve(foo()).then(result => console.log(result))
console.log("lo");
function foo() {
console.log("hi");
return 1;
}
const result = foo();
setTimeout(() => console.log(result));
console.log("lo");
In all three cases the console logs hi, lo, 1. Before 1 is printed the UI can handle user input or draw updates. The reason 1 that is printed last in the first two cases is that callbacks for promises are not executed immediately.
await
allows you to do that without callbacks:
async function foo() {
console.log("hi");
return 1;
}
async function bar() {
const result = await foo();
console.log(result);
}
bar();
console.log("lo");
That will also print hi, lo, 1. Much like a callback for a promise, the code after await
is never executed immediately.
setTimeout
, an XHR response, or event a click event: jsfiddle.net/wgqyayhr (Demo needs a browser with support) – Mcculloughasync/await
is not part of ES7 (ES2016). It will be part of this year's release, ES2017. – Buhr