This blog post gives tips for error handling in asynchronous, Promise-based functions.
2. Handling exceptions in Promise-based functions
2.1 Solution 1: returning a rejected Promise
function asyncFunc() { try { doSomethingSync(); return doSomethingAsync() .then(result => { ··· }); } catch (err) { return Promise.reject(err); } }
2.2 Solution 2: executing the sync code inside a callback
You can also start a chain of then() method calls via Promise.resolve() and execute the synchronous code inside a callback:
function asyncFunc() { return Promise.resolve() .then(() => { doSomethingSync(); return doSomethingAsync(); }) .then(result => { ··· }); }
An alternative is to start the Promise chain via the Promise constructor:
function asyncFunc() { return new Promise((resolve, reject) => { doSomethingSync(); resolve(doSomethingAsync()); }) .then(result => { ··· }); }
















