JS Coding Questions Logo
JS Coding Questions
#415💼 Interview💻 Code

How do you check an object is a promise or not

Advertisement

728x90

If you don't know if a value is a promise or not, wrapping the value as Promise.resolve(value) which returns a promise

javascript
1function isPromise(object) {
2
3if (Promise && Promise.resolve) {
4  return Promise.resolve(object) == object;
5} else {
6  throw "Promise not supported in your environment";
7}
8}
9
10var i = 1;
11
12var promise = new Promise(function (resolve, reject) {
13
14resolve();
15});
16
17console.log(isPromise(i)); // false
18
19console.log(isPromise(promise)); // true

Another way is to check for .then() handler type

javascript
1function isPromise(value) {
2
3return Boolean(value && typeof value.then === "function");
4}
5
6var i = 1;
7
8var promise = new Promise(function (resolve, reject) {
9
10resolve();
11});
12
13console.log(isPromise(i)); // false
14
15console.log(isPromise(promise)); // true

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 72

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
415of476