Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the difference between Python async and JavaScript native async

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

Today, I would like to share with you the relevant knowledge about the difference between Python asynchronism and JavaScript native asynchronism. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

Now suppose we want to request a URL: http://httpbin.org/delay/5. After this request, we need to wait 5 seconds for the result to be returned. We use jQuery to write a piece of JavaScript code:

Function test_async () {$.ajax ({type: 'GET', contentType:' application/json Charset=utf-8', url: 'http://httpbin.org/delay/5', success: function (response) {console.log (' 5 second request returns:', response)}) var a = 1 + 1 a = a * 2 console.log (a) $.ajax ({type: 'GET', contentType:' application/json Charset=utf-8', url: 'http://httpbin.org/ip', success: function (response) {console.log (' query IP returns:', response)}) console.log ('here is the end of the code')}

The running effect is shown in the following figure:

As you can see, the execution logic of the whole code is consistent with the asynchronism in our lives, first initiating a five-second request, but the program does not get stuck waiting, but continues to run the following code, and then initiates a new request. Due to the short return time of the new request, the new request is quickly returned and printed, and finally the result of the printed 5-second request is returned.

This is like we turned on the power of the washing machine, then went to Taomi to cook, the rice was put into the electric cooker, turned on the electric cooker, then went to read, and finally the meal was cooked first, and then the clothes were washed.

The process of JavaScript's native asynchronous request is very similar to the logic of daily life. So it's easy to understand the asynchronous flow of JavaScript.

But in Python, asynchrony is a different story.

Let's write a piece of code:

Import asyncio import aiohttp async def main (): async with aiohttp.ClientSession () as client: response = await client.get ('http://httpbin.org/delay/5') result = await response.json () print (' 5 seconds request returns:' Result) a = 1 + 1 a = a * 2 print (a) new_response = await client.get ('http://httpbin.org/ip') new_result = await new_response.json () print (' query IP returns:', new_result) print ('here is the end of the code') asyncio.run (main ())

The running effect is shown in the following figure:

It can be seen that the program is still running serially, and there is no trace of asynchronism at all.

For the program to run asynchronously, we need to scrape together a batch of tasks to be submitted to asyncio and let it schedule them through an event loop:

Import asyncio import aiohttp async def do_plus (): a = 1 + 1 a = a * 2 print (a) async def test_delay (client): response = await client.get ('http://httpbin.org/delay/5') result = await response.json () print (' 5 seconds request returns:' Result) async def test_ip (client): response = await client.get ('http://httpbin.org/ip') result = await response.json () print (' query IP returns:', result) async def test_print (): print ('here is the end of the code') async def main (): async with aiohttp.ClientSession () as client: tasks = [asyncio.create_task (test_delay (client)) Asyncio.create_task (do_plus ()), asyncio.create_task (test_ip (client)), asyncio.create_task (test_print ()) await asyncio.gather (* tasks) asyncio.run (main ())

The running effect is shown in the following figure:

This is because, in asyncio, task is the smallest unit that can be parallelized, and task has to scrape together a batch to submit to the event loop through asyncio.gather or asyncio.wait before it can be parallelized.

When using the code asyncio.create_task (asynchronous function ()), the asynchronous function doesn't actually run, so in the above code:

Tasks = [asyncio.create_task (test_delay (client)), asyncio.create_task (do_plus ()), asyncio.create_task (test_ip (client)), asyncio.create_task (test_print ())]

A list of four task is created, and the code in none of the four asynchronous functions has yet to be executed.

When await asyncio.gather (* tasks) is called again, these four tasks are passed into the asyncio.gather function as four parameters, and Python's event loop begins to schedule them. Among these asynchronous functions, where await is included, you are telling Python,await that there may be IO waiting for the following function. You can hang it for a while, and now you can check whether other asynchronous tasks in the event loop have finished waiting for you to run. Where there is no await, it is still serial. For example, the three lines of code in do_plus are run sequentially at once.

Therefore, when we use Python's asyncio to write asynchronous code, we need to arrange the asynchronous switching location in advance and package it as asynchronous tasks, and then submit a batch of tasks to asyncio at one time, and let Python schedule these tasks according to the switching logic we arranged.

It's like, when I write JavaScript, I personally turn on the washing machine, and then I think about what I'm going to do with the waiting time.

When I write Python, I need to arrange the whole plan in advance: turn on the washing machine, cook rice while I'm waiting, and then read a book. And submit the schedule to a person who specializes in doing things for execution.

That's all of the article "what's the difference between Python Asynchronous and JavaScript Native Asynchronous". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report