I am not able to catch the Exception/Error that is happening inside of the Resolve promise. Can someone explain if there is a way to catch this error:
createAsync = function() {
var resolve, reject,
promise = new Promise(function(res, rej) {
resolve = res;
reject = rej;
});
promise.resolve = resolve;
promise.reject = reject;
return promise;
};
promise = createAsync()
promise.then(function myresolver(){
throw Error('wow')
})
// Catching the error here
try {
promise.resolve()
} catch(err) {
console.log( 'GOTCHA!!', err );
}
EDIT:
Let me explain me better, I'm trying to create an API and the user only have access to the promise resolve/reject part:
// This is my API user does not have access to this part
promise = createAsync()
promise
.then(function(fun) {
if (typeof fun != 'function')
throw Error('You must resolve a function as argument')
}).catch(function(err){
// Some internal api tasks...
return Promise.reject(err)
})
Now the solution I would like to give him, but does not work:
// Here is where the user can resolve the promise.
// But must be able to catch the error
promise.catch(function(err){
console.log("GOTCHA", err)
})
promise.resolve('This must be a function but is a string');
Any ideas?
More info: Yes is an antipattern for the common usage. This is a remote procedure call API, so the user must be able to reject or resolve. And the calls are async so the best approach is to use promises. I wouldn't say is an antipattern for this case. Actually is the only pattern. (I can't use Async/Await)
// Catching the error here
no you aren't - youpromise.resolve()
doesn't reject the promise ... yourpromise.then ... throw
will "reject" THAT promise (the one returned by .then) not the one inpromise
– Jaromanda Xresolve
andreject
functions provided to the executor (the function passed to the promise constructor), in your case by polluting the promise object with additional properties, is an anti-pattern. The entire point of the design of the promise constructor is that resolving and rejecting is isolated within the executor. Your approach allows any random person who happens to acquire one of your promise objects to resolve or reject it, which is almost certainly not good program design. – user663031resolve
orreject
- the better promise pattern is to simply accept a promise from the user that he can resolve/reject at his own disposal. – BergicreateAsync
pseudocode. – Bergif
in thatlocalProcedureCall
was and how it uses/needs to use thereq
object. However, I can tell you thatlocalProcedureCall
should not takeresolve
andreject
callbacks but rather return a promise (and you likely want to use.then(…, …)
instead of.then(…).catch(…)
), and that the pattern fordop.protocol.subscribe
basically should look likereturn new Promise(resolve => storeRequest(node, request_info, resolve); })
– Bergi