If you don’t know if a value is a promise or not, wrapping the value as Promise.resolve(value) which returns a promise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function isPromise(object){ if(Promise && Promise.resolve){ return Promise.resolve(object) == object; }else{ throw "Promise not supported in your environment" } } var i = 1; var promise = new Promise(function(resolve,reject){ resolve() }); console.log(isPromise(i)); // false console.log(isPromise(p)); // true |
Another way is to check for .then()
handler type
1 2 3 4 5 6 7 8 9 10 | function isPromise(value) { return Boolean(value && typeof value.then === 'function'); } var i = 1; var promise = new Promise(function(resolve,reject){ resolve() }); console.log(isPromise(i)) // false console.log(isPromise(promise)); // true |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.