I like JavaScript promises. But I'm not too crazy about the ES6 way
(see MSDN) where
you get the resolve and reject as parameter of a function:
function doSomethingAsync() { return new Promise(function(resolve, reject) { callAsncCode(xyz, function(result) { if(<result is ok>) { resolve(someData); } else { reject(); } }); }); }I would rather have something like this:
function doSomethingAsync() { var promise = <gimme a promise> callAsncCode(xyz, function(result) { if(<result is ok>) { promise.resolve(someData); } else { promise.reject(); } }); return promise; }To get this I always have this small ES6 class in my tool belt:
class SimplePromise { constructor() { const self = this; this._promise = new Promise(function(resolve, reject) { self._resolve = resolve; self._reject = reject; }); } resolve(data) { this._resolve(data); } reject(data) { this._reject(data); } promise() { return this._promise; } }Now my code looks like this:
function doSomethingAsync() { var promise = new SimplePromise(); callAsncCode(xyz, function(result) { if(<result is ok>) { promise.resolve(someData); } else { promise.reject(); } }); return promise.promise(); }Not everyone may like it. I do.