Using setTimeout on promise chain

To keep the promise chain going, you can’t use setTimeout() the way you did because you aren’t returning a promise from the .then() handler – you’re returning it from the setTimeout() callback which does you no good. Instead, you can make a simple little delay function like this: And, then use it like this: Here … Read more

Why is my asynchronous function returning Promise { } instead of a value?

The promise will always log pending as long as its results are not resolved yet. You must call .then on the promise to capture the results regardless of the promise state (resolved or still pending): Why is that? Promises are forward direction only; You can only resolve them once. The resolved value of a Promise is passed to its .then or .catch methods. … Read more

Using async/await with a forEach loop

Sure the code does work, but I’m pretty sure it doesn’t do what you expect it to do. It just fires off multiple asynchronous calls, but the printFiles function does immediately return after that. Reading in sequence If you want to read the files in sequence, you cannot use forEach indeed. Just use a modern for … of loop instead, in which await will … Read more

How to wait for a JavaScript Promise to resolve before resuming function?

I’m wondering if there is any way to get a value from a Promise or wait (block/sleep) until it has resolved, similar to .NET’s IAsyncResult.WaitHandle.WaitOne(). I know JavaScript is single-threaded, but I’m hoping that doesn’t mean that a function can’t yield. The current generation of Javascript in browsers does not have a wait() or sleep() that allows other things … Read more

What is the difference between Promises and Observables?

Promise A Promise handles a single event when an async operation completes or fails. Note: There are Promise libraries out there that support cancellation, but ES6 Promise doesn’t so far. Observable An Observable is like a Stream (in many languages) and allows to pass zero or more events where the callback is called for each event. Often Observable is preferred over Promise because it provides the features of Promise and more. With Observable it doesn’t … Read more

Syntax for an async arrow function

Async arrow functions look like this: Async arrow functions look like this for a single argument passed to it: Async arrow functions look like this for multiple arguments passed to it: The anonymous form works as well: An async function declaration looks like this: Using async function in a callback: Using async method inside of a class: