JS ES6 Promise Chaining

后端 未结 5 2069
南笙
南笙 2020-12-10 14:28

I\'m trying to learn how to use promises, but am having trouble comprehending the chaining. I assume that with this code, both promises will run. Then when I call test.then(

5条回答
  •  轮回少年
    2020-12-10 14:53

    You may also want to try -

        let test = new Promise(function(resolve, reject){
            resolve('done1');
        });
    
        let test2 = new Promise(function(resolve, reject){
            resolve('done2');
        });
    
        try {
            let logOne = test();
            let logTwo = test2();
            console.log(logOne);
            console.log(logTwo);
        } catch(error) {
            console.error(error);
        }
    

    In this way, you can also properly handle any promise dependencies. For example if test one relied on test two's data your could -

    try {
            let logOne = test();
            let logTwo = test2(logOne);
            console.log(logOne);
            console.log(logTwo);
        } catch(error) {
            console.error(error);
        }
    

提交回复
热议问题