After performing an operation async, await requests return of all the analog

Before the project encountered such a demand, the front page there is a lot of need to back-end data request, when all requests to return the following actions will continue, I think other people are using nested written request to engage in, but between these requests and no dependencies, this will lead to a waste of efficiency, today learned a trick you can use to return Promise.all a new promise, the Code

<script>
        function timer(timeout,name)
        {
        	// 这里用定时器模拟,可以换为ajax请求
            return new Promise(resolve => {
                setTimeout(()=>{
                    console.log(name)
                },timeout);
            })
        }

        async function allP()
        {
            let p1 = timer(1000,'请求1');
            let p2 = timer(1000,'请求2');
            let p3 = timer(1000,'请求3');
            await Promise.all([p1,p2,p3]);
        }
        allP();
    </script>

If synchronized way to do 3 seconds, and do 1 second on the return

Published 236 original articles · won praise 10 · views 10000 +

Guess you like

Origin blog.csdn.net/gunsmoke/article/details/104583112