JavaScriptLesson 15 of 16
Promises and async/await
A server, a file or a timer never answers instantly, and a program should not freeze while it waits. A promise stands for a value that arrives a bit later, and await lets you wait for it as if the code ran in order.
Key points
- new Promise((resolve, reject) => …): resolve hands over the result, reject an error
- An async function always returns a promise, and await inside it waits for the result
- Errors from await are caught with an ordinary try...catch
- The order: all plain code first, then promises, then timers, even setTimeout with 0
- Promise.all([…]) waits for several promises at once
Example
console.log("1: code runs top to bottom");setTimeout(() => console.log("4: a timer, even with 0 ms"), 0);Promise.resolve().then(() => console.log("3: a resolved promise"));console.log("2: still the same pass"); const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); async function later() { await wait(0); console.log("5: after await"); return "result";} later().then((value) => console.log("6:", value));The numbers show the real order: the plain lines, then the promise, then the timer. later() waited for a timer with await, and its return value went to then.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.Finish track(id): wait for getOrder(id) with await and print Order 7: Margherita in 20 min, and if the order does not exist, catch the error with try...catch and print its message. Output: Checking orders..., Order 7: Margherita in 20 min, Order 9 not found and All done.
Output
What your program prints appears here.