Asynchronous processing is to handle problems according to asynchronous procedures. Asynchronous processing and synchronous processing are opposites, and what produces them is multi-threading or multi-process. The benefit of asynchronous processing is to increase device utilization, thereby improving program operation efficiency at a macro level, but the disadvantage is that conflicting operations and dirty data reading are prone to occur. In this article, we will share with you about asynchronous processing in JavaScript.
In the world of JavaScript, all code is executed in a single thread. Due to this "flaw", all network operations and browser events in JavaScript must be executed asynchronously. Asynchronous execution can be implemented using callback functions
Asynchronous operations will trigger a function call at a certain point in the future
The mainstream asynchronous processing solutions mainly include: callback function (CallBack), Promise, Generator Functions, async/await.
1. Callback function (CallBack)
This is the most basic method of asynchronous programming
Suppose we have a getData method, which is used to obtain data asynchronously. The first parameter is the URL address of the request, and the second parameter is the callback function, as follows:
function getData(url, callBack){ // 模拟发送网络请求 setTimeout(()=> { // 假设 res 就是返回的数据 var res = { url: url, data: Math.random() } // 执行回调,将数据作为参数传递 callBack(res) }, 1000) }
We set a scenario in advance, assuming that we want to request the server three times, and each request depends on the result of the previous request, as follows:
getData('/page/1?param=123', (res1) => { console.log(res1) getData(`/page/2?param=${res1.data}`, (res2) => { console.log(res2) getData(`/page/3?param=${res2.data}`, (res3) => { console.log(res3) }) }) })
As can be seen from the above code, the url address of the first request is: /page/1?param=123, and the returned result is res1.
The url address of the second request is: /page/2?param=${res1.data}, which depends on the res1.data of the first request, and the returned result is res2`.
The url address of the third request is: /page/3?param=${res2.data}, which depends on the res2.data of the second request, and the returned result is res3.
Since subsequent requests depend on the result of the previous request, we can only write the next request inside the callback function of the previous request, thus forming what is often said: callback hell.
2. Publish/Subscribe
We assume that there is a "signal center". When a certain task is completed, a signal is "published" to the signal center, and other tasks can be sent to the signal center. The signal center "subscribes" to this signal so that it knows when it can start execution. This is called the "publish-subscribe pattern" (publish-subscribe pattern), also known as the "observer pattern" (observer pattern)
There are many implementations of this pattern. The following is Ben Alman's Tiny Pub/ Sub, this is a plug-in for jQuery
First, f2 subscribes to the "Signal Center" jQuery "done" signal
jQuery.subscribe("done", f2);
f1进行如下改写 function f1(){ setTimeout(function(){ // f1的任务代码 jQuery.publish("done"); }, 1000);} jQuery.publish("done") 的意思是, f1 执行完成后,向”信号中心 "jQuery 发布 "done" 信号,从而引发f2的执行。 此外,f2完成执行后,也可以取消订阅( unsubscribe ) jQuery.unsubscribe("done", f2);
The nature of this method is similar to "Event Listening", but it is obviously better to the latter. Because we can monitor the operation of the program by looking at the "Message Center" to see how many signals exist and how many subscribers each signal has.
3. Promise
Promise is a solution for asynchronous programming, which is more reasonable and powerful than traditional solutions - callback functions and events.
So-called Promise, simply put, is a container that stores the result of an event (usually an asynchronous operation) that will end in the future. Syntactically speaking, Promise is an object from which messages for asynchronous operations can be obtained. Promise provides a unified API, and various asynchronous operations can be processed in the same way
Simply put, the idea is that each asynchronous task returns a Promise object, which has a then method that allows specifying Callback.
Now we use Promise to re-implement the above case. First, we need to encapsulate the method of asynchronously requesting data into Promise
function getDataAsync(url){ return new Promise((resolve, reject) => { setTimeout(()=> { var res = { url: url, data: Math.random() } resolve(res) }, 1000) }) }
Then the request code should be written like this
getDataAsync('/page/1?param=123') .then(res1=> { console.log(res1) return getDataAsync(`/page/2?param=${res1.data}`) }) .then(res2=> { console.log(res2) return getDataAsync(`/page/3?param=${res2.data}`) }) .then(res3=> { console.log(res3) })
The then method returns a new Promise object. The chained calling of the then method avoids CallBack hell
But it is not perfect. For example, if we need to add a lot of then statements, we still need to write a callback for each then.
If the scenario is more complicated, for example, each subsequent request depends on the results of all previous requests, not just the results of the previous request, it will be more complicated. In order to do better, async/await came into being. Let's see how to use async/await to achieve
4. async/await
getDataAsync method remains unchanged, as follows
function getDataAsync(url){ return new Promise((resolve, reject) => { setTimeout(()=> { var res = { url: url, data: Math.random() } resolve(res) }, 1000) }) }
The business code is as follows
async function getData(){ var res1 = await getDataAsync('/page/1?param=123') console.log(res1) var res2 = await getDataAsync(` /page/2?param=${res1.data}`) console.log(res2) var res3 = await getDataAsync(`/page/2?param=${res2.data}`) console.log(res3)
}
You can see that using async\await is just like writing synchronous code
How do you feel about comparing Promise? Is it very clear, but async/await is based on Promise, because the method decorated with async ultimately returns a Promise. In fact, async/await can be seen as using the Generator function to handle asynchronous syntactic sugar. Let’s take a look at how to use it. Generator function handles asynchronous
5. Generator
First of all, the asynchronous function is still
function getDataAsync(url){ return new Promise((resolve, reject) => { setTimeout(()=> { var res = { url: url, data: Math.random() } resolve(res) }, 1000) }) }
Using the Generator function can be written like this
function*getData(){ var res1 = yield getDataAsync('/page/1?param=123') console.log(res1) var res2 = yield getDataAsync(`/page/2?param=${res1.data}`) console.log(res2) var res3 = yield getDataAsync(`/page/2?param=${res2.data}`) console.log(res3)) }
Then we execute it step by step
var g = getData() g.next().value.then(res1=> { g.next(res1).value.then(res2=> { g.next(res2).value.then(()=> { g.next() }) }) })
上面的代码,我们逐步调用遍历器的 next() 方法,由于每一个 next() 方法返回值的 value 属性为一个 Promise 对象
所以我们为其添加 then 方法, 在 then 方法里面接着运行 next 方法挪移遍历器指针,直到 Generator 函数运行完成,实际上,这个过程我们不必手动完成,可以封装成一个简单的执行器
function run(gen){ var g = gen() function next(data){ var res = g.next(data) if (res.done) return res.value res.value.then((data) => { next(data) }) } next() }
run 方法用来自动运行异步的 Generator 函数,其实就是一个递归的过程调用的过程。这样我们就不必手动执行 Generator 函数了。 有了 run 方法,我们只需要这样运行 getData 方法
run(getData)
这样,我们就可以把异步操作封装到 Generator 函数内部,使用 run 方法作为 Generator 函数的自执行器,来处理异步。其实我们不难发现, async/await 方法相比于 Generator 处理异步的方式,有很多相似的地方,只不过 async/await 在语义化方面更加明显,同时 async/await 不需要我们手写执行器,其内部已经帮我们封装好了,这就是为什么说 async/await 是 Generator 函数处理异步的语法糖了
以上内容就是关于JavaScript中的异步处理,希望能帮助到大家。
相关推荐:
The above is the detailed content of Asynchronous processing analysis in JavaScript. For more information, please follow other related articles on the PHP Chinese website!