Do I need to return after early resolve/reject?

The return purpose is to terminate the execution of the function after the rejection, and prevent the execution of the code after it. function divide(numerator, denominator) { return new Promise((resolve, reject) => { if (denominator === 0) { reject(“Cannot divide by 0”); return; // The function execution ends here } resolve(numerator / denominator); }); } … Read more

What’s the difference between returning value or Promise.resolve from then()

In simple terms, inside a then handler function: A) When x is a value (number, string, etc): return x is equivalent to return Promise.resolve(x) throw x is equivalent to return Promise.reject(x) B) When x is a Promise that is already settled (not pending anymore): return x is equivalent to return Promise.resolve(x), if the Promise was … Read more

Resolve promises one after another (i.e. in sequence)?

Update 2017: I would use an async function if the environment supports it: async function readFiles(files) { for(const file of files) { await readFile(file); } }; If you’d like, you can defer reading the files until you need them using an async generator (if your environment supports it): async function* readFiles(files) { for(const file of … Read more

How to check if an object is a Promise?

How a promise library decides If it has a .then function – that’s the only standard promise libraries use. The Promises/A+ specification has a notion called thenable which is basically “an object with a then method”. Promises will and should assimilate anything with a then method. All of the promise implementation you’ve mentioned do this. … Read more

jQuery deferreds and promises – .then() vs .done()

The callbacks attached to done() will be fired when the deferred is resolved. The callbacks attached to fail() will be fired when the deferred is rejected. Prior to jQuery 1.8, then() was just syntactic sugar: promise.then( doneCallback, failCallback ) // was equivalent to promise.done( doneCallback ).fail( failCallback ) As of 1.8, then() is an alias … Read more