JavaScript - Returning AND / OR callbackback promises?

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.?

+5
source share
1 answer

This can be simplified if you just always used the promise you always make:

 export function doSomeAsync(options, callback) { const promise = new Promise((resolve, reject) => { const check = (options.num === 1) ? true : false; setTimeout(() => { if (check) { resolve("Number is 1"); } else { reject(new Error("Number is not 1")); } }, 1000); }); if (callback && typeof callback == 'function') { promise.then(callback.bind(null, null), callback); } return promise; } 

Your function is always based on promises, and also that it always returns a promise. The caller may simply ignore this. The callback argument is simply a "backspace interface" (or an "alternative interface" if you prefer) to use this promise.

+10
source

Source: https://habr.com/ru/post/1247857/


All Articles