I often see in other nations something like:
Callback is optional; if omitted, a promise is returned.
This is what I have:
export function doSomeAsync(options, callback) { const useCallback = (callback && typeof callback == 'function'); const promise = new Promise((resolve, reject) => { // --- do async stuff here --- const check = (options.num === 1) ? true : false; setTimeout(() => { if (check) { finish(true, "Number is 1"); } else { finish(false, new Error("Number is not 1")); } }, 1000); // --------------------------- function finish(ok, rtn) { if (useCallback) { if (ok) { callback(null, rtn); } else { callback(rtn, null); } } else { if (ok) { resolve(rtn); } else { reject(rtn); } } } }); return (useCallback) ? false : promise; }
The finish() function simply avoids the many if... scattered around.
I create a promise object, regardless of whether I use it.
Testing as follows:
doSomeAsync({ num: 1 }).then((result) => { console.log('p result', result); }).catch((err) => { console.log('p err', err); }); doSomeAsync({ num: 1 }, (err, result) => { if (err) { console.log('cb err', err); } else { console.log('cb result', result); } });
This works, but I wonder if this is a better way, or if others have a better and more concise implementation.?
source share