Running code inside another thread in javascript

后端 未结 4 1318
-上瘾入骨i
-上瘾入骨i 2021-02-07 09:18

I want to seperate thread on the page to prevent freezing of gui. For this, I am running the function which will freeze gui inside another thread with setTimeout but still freez

4条回答
  •  孤独总比滥情好
    2021-02-07 09:42

    You can use "Promise" to operate asynchronous function(s):

    Promise document

    A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

    Step 1:

    const dosomethingPromise = (data, otherInput) => {
    return new Promise((resolve, reject) => {
         /* do your work here*/
        resolve(true) /* return result here or you can use reject for execute catch block*/
    })
    

    };

    Step 2: use it like this in your code:

     Promise.resolve(dosomethingPromise(data,otherInput))
            .then((result) => {
                /*your result come here*/
                console.log("Progress finished=>", result);
            }, (error) => {
                console.log(error)
            })
            .catch(console.log);
    

    you can also use Promise and the "all" method instead of "resolve" method to do multiple tasks in a row and get your final result.

提交回复
热议问题