3 ms·
const apiCall = url => fetch(url); const timeout = time => { return new Promise((resolve, reject) => { setTimeout(() => reject('Promise timed out')
by wruza 7y ago
const 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.