3 ms·
What You Need to Know About Asynchronous Programming in JavaScript
- wruza 7y agolet orders; // initialized in outer scope db.getUser(id) .then(user => db.getOrders(user)) .then(orders => db.getProducts(orders[0])) .then(products => { // orders is now accessible here! }) No, it isn't.
- wruza 7y agoconst apiCall = url => fetch(url); const timeout = time => { return new Promise((resolve, reject) => { setTimeout(() => reject('Promise timed out'), time); }); }; Promise.race([apiCall, timeout]) .then(response => { // response from apiCall was successful }) .catch(err => { // handle the timeout }); This code doesn't do anything, since neither 'apiCall', nor 'timeout' are promises themselves. It just resolves with (response === apiCall). >You can’t afford to get this wrong. >Throughout my career I’ve been in a lot of job interviews, both as an interviewer and as a candidate. I’ve seen my share of candidates fall apart when asked to code asynchronous code using Promises and async/await. An interview is more stressful than writing an educational blog post, and yet it failed at its purpose twice.