Returning from the Promise constructor (or any function inside it) does not resolve the promise:
return new Promise(function(resolve, reject) { sdk.refreshTokens(..., function(err, new_tokens) { if(error.code === 'invalid_grant') { return authorize_with_api(); }
Even if you did not have a return from the sdk.refreshTokens and instead had a direct return authorize_with_api() without a callback, the result would still not get the chain.
To resolve a promise, you cannot return from your constructor, but you must explicitly call one of the given callbacks (allow / reject):
return new Promise(function(resolve, reject) { sdk.refreshTokens(..., function(err, new_tokens) { if(error.code === 'invalid_grant') { resolve(authorize_with_api()); }
The resolution of the promise actually also eliminates the rejection, so regardless of whether authorize_with_api is allowed or rejected, the state will appropriately distribute the chain.
My suggestion is to still support the return order to support the alleged visual semantics of forming the if branch, early return, but the code will work without it, because promises can only be resolved once, and all further reject / resolve calls are ignored .
return new Promise(function(resolve, reject) { sdk.refreshTokens(..., function(err, new_tokens) { if(error.code === 'invalid_grant') { return resolve(authorize_with_api()); }
Examples:
function success() { return Promise.resolve('success'); } function error() { return Promise.reject('error'); } function alwaysPending() { return new Promise(() => { return success(); }); } function resolves() { return new Promise((resolve) => { resolve(success()); }); } function rejects() { return new Promise((resolve) => { resolve(error()); }); } alwaysPending().then(console.log);
source share