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

前端 未结 3 1094
挽巷
挽巷 2020-12-16 05:29

Say I have two functions:

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

function f2() {
}
         


        
3条回答
  •  粉色の甜心
    2020-12-16 06:11

    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)});

提交回复
热议问题