How do I check if a JavaScript function returns a Promise?

Say I have two functions:

function f1() {
    return new Promise<any>((resolve, reject) => {
        resolve(true);
    });
}

function f2() {
}

How do I know if f1 will return Promise and f2 will not?

Answers:

Answer

Call the function, use instanceof

let possiblePromise = f1();
let isPromise = possiblePromise instanceof Promise;
Answer

So it's just about normalizing the output. Then run it through Promise.resolve() and co.

var possiblePromise = f1();
var certainPromise = Promise.resolve(possiblePromise).then(...);

or

var possiblePromises = [f1(), f2()];
Promise.all(possiblePromises).then(values => ...);

But you need to have a basic Idea of what these functions return. For Example: Both examples would fail with

function f3(){
    return [somePromise, someOtherPromise];
}

var arrayOfPromisesOrValues = f3();

//here you'll still deal with an Array of Promises in then();
Promise.resolve(arrayOfPromisesOrValues).then(console.log); 
//neither does this one recognize the nested Promises
Promise.all([ f1(), f2(), f3() ]).then(console.log);

//only these will do:
Promise.all(f3()).then(console.log);
Promise.all([ f1(), f2(), Promise.all(f3()) ]).then(console.log);

You need to know that f3 returns an Array of Promises or values and deal with it. Like you need to know that f1 and f2 return a value or a Promise of a value.

Bottom line: you need to have a basic knowledge of what a function returns to be able to run the result through the proper function to resolve the promises.

Answer

This can't be done.

You can, however, cast any function to a Promise-returning function. This is what I'd do here.

const toPromise = function (f) {
  return function () {
    return new Promise((resolve, reject) => {
      const result = f.apply(null, Array.from(arguments));
      try {
        return result.then(resolve, reject); // promise.
      } catch (e) {
        if (e instanceof TypeError) {
          resolve(result); // resolve naked value.
        } else {
          reject(e); // pass unhandled exception to caller.
        }
      }
    });
  };
};

const f = (x) => x;
const g = (x) => Promise.resolve(x);
const h = (x) => Promise.reject(x);

// Naked value.
toPromise(f)(1).then((x) => {console.log(x)});
// Resolved Promise.
toPromise(g)(2).then((x) => {console.log(x)});
// Rejected Promise.
toPromise(h)(3).catch((x) => {console.log(x)});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.