当前位置:网站首页>Promise processing JS multithreads get the same processing result after all the results are obtained

Promise processing JS multithreads get the same processing result after all the results are obtained

2022-06-13 04:40:00 AF01

html Code

<!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 feb(n) {
            if (n == 1 || n == 2) {
                return 1
            }
            return feb(n - 1) + feb(n - 2)
        }
        let a = +new Date();
        let n1 = 30;
        let data2 = feb(n1)
        console.log(data2);
        console.log(' Multithreading not turned on single time consuming :',+new Date() - a);


        let time1 = +new Date();
        let promiseArr = []
        for (let index = 0; index < 13; index++) {
            let worker = new Worker('worker.js')
            let p = new Promise((resolve, reject) => {
                worker.postMessage(n1)
                worker.onmessage = e => {
                    resolve(e.data)
                }
                worker.onerror = error => {
                    reject(error)
                }
            })
            promiseArr.push(p);
            n1++;
        }


        console.log(promiseArr);
        Promise.all(promiseArr).then(data => {
            console.log(data);
            console.log(' Time consuming to turn on Multithreading :',+new Date() - time1);
        })

    </script>
</body>

</html>

worker.js

function feb(n) {
    if (n==1||n==2) {
        return 1
    }
    return  feb(n-1)+feb(n-2)
}
let a = +new Date();
let n= 2;
self.onmessage = function(event) {
    n = event.data;
    console.log("onmessage:",event.data);
    let data1 =  feb(n)
    console.log(+new Date()-a);
    self.postMessage(data1)
    self.close();
};

原网站

版权声明
本文为[AF01]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/164/202206130436444079.html