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

前端 未结 3 1095
挽巷
挽巷 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 05:57

    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.

    0 讨论(0)
  • 2020-12-16 06:11

    Call the function, use instanceof

    let possiblePromise = f1();
    let isPromise = possiblePromise instanceof Promise;
    
    0 讨论(0)
  • 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)});

    0 讨论(0)
提交回复
热议问题