Node.jsQuestion 08 of 26
Promise
Answer out loud or in your head first, then compare.
Answer
A Promise represents the future result of an operation. It is pending, then fulfilled or rejected. Once settled, its result no longer changes.
JavaScript
const delay = ms => new Promise(resolve => {
setTimeout(resolve, ms);
});
delay(200).then(() => console.log('Done'));To be precise: the function passed to the Promise constructor runs synchronously. .then() handlers run as microtasks.
Pitfall: I don't wrap a function that already returns a Promise in new Promise. I also remember to return the result in a chain, so the next step waits for it.
How did it go? Be honest — “Not yet” puts the question on your review list.
Related questions
- B-P04 · What is a Promise? — JavaScript, TypeScript and Node.js