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

前端 未结 3 1102
挽巷
挽巷 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.

提交回复
热议问题