Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现Promise.all #37

Open
zuopf769 opened this issue Apr 26, 2023 · 0 comments
Open

实现Promise.all #37

zuopf769 opened this issue Apr 26, 2023 · 0 comments

Comments

@zuopf769
Copy link

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>

        function getPromise(value, time) {
            return new Promise((r,j) => {
                setTimeout(() => {
                    r(value)
                }, time);
            });
        }

        Promise.all = function(promises) {
            // 返回一个新的promise
            return new Promise((resolve, reject) => {
                // 存储所有promise结果的数组
                let result = [];
                // 参数中的promise的个数
                let count = promises.length;
                // 计数器
                let time = 0;

                // 处理数据
                function processData(i, data) {
                    result[i] = data;
                    // 数据都处理完毕后,resolve返回结果
                    if (++time >= count) {
                        resolve(result);
                    }
                }

                // 遍历参数中传入的promises
                for (let i = 0; i < count; i++) {
                    let cur = promises[i];
                    // 处理每个promise的结果;成功就放到result中,如果有一个失败就整体失败
                    Promise.resolve(cur).then((data) => {
                        // 处理数据,因为需要记录顺序所以需要传i
                        processData(i, data);
                    }, reject);
                }

            })
        }

        let promise1 = getPromise(1, 1000);
        let promise2 = getPromise(2, 2000);
        let promise3 = getPromise(3, 3000);

        Promise.all([promise1, promise2, promise3]).then((data) => {
            console.log(data);
        })

    </script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant