check if function is async javascript 1

check if function is async javascript

let promise = fnThatYouWannaCheck();

if(promise && typeof promise.then === 'function' 
   && promise[Symbol.toStringTag] === 'Promise')
{
  	// is compliant native promise implementation
}
else
{
  	throw new Error('async function expected');
}

Here is what the above code is Doing:
1. It checks if the function returns a promise.
2. It checks if the promise has a then method.
3. It checks if the promise has a Symbol.toStringTag property.

The Symbol.toStringTag property is a string that is returned by the toString() method of the object.

For example, if you run the following code:

let promise = new Promise(function(resolve, reject) {
resolve(1);
});

console.log(promise.toString());

// Output: [object Promise]

Similar Posts