0

I want to know why this example doesn't work asynchronously ? and what I should change that to make it work. I will really appreciate for any help !

Example 1:

import asyncio
import random
import time


nums = list()
[nums.append(x) for x in range(1, 100)]
random_time = random.randint(1, 5)

async def func(num):
    num = num * 2
    time.sleep(random_time)
    print(num)
    return num

async def main():
    tasks = list()
    for num in nums:
        tasks.append(func(num))
    return await asyncio.gather(*tasks)

loop = asyncio.get_event_loop()
results = loop.run_until_complete(main())
loop.close()
print(f'{len(results)} are asynchronized')

Example 2:

enter image description here

ppostnov
  • 139
  • 9
  • 4
    Your task (`func`) isn't `await`ing anything, it's a normal blocking function. You'll want to use `asyncio.sleep` if you want an asynchronous, non-blocking sleep. – deceze Oct 01 '20 at 07:40
  • Would you kindly read [the answer here](https://stackoverflow.com/questions/33357233/when-to-use-and-when-not-to-use-python-3-5-await)? I believe it may help. – Mikhail Gerasimov Oct 01 '20 at 08:11
  • ok, thanks, all ok with first example – ppostnov Oct 01 '20 at 08:32
  • but what about second example ? what's wrong ? – ppostnov Oct 01 '20 at 08:34
  • 2
    Second issue is exactly the same thing. Even if you wrap the method in an `async/await` function, that's not changing anything. The actual function itself is blocking. You'd need to find a jira library that works with asyncio and enables you to `await issue.update(...)` for example. You can use executors to run blocking calls in an async fashion: https://stackoverflow.com/q/41063331/476 – deceze Oct 01 '20 at 08:41
  • Please don't post pictures of code, as they cannot be searched or edited. – user4815162342 Oct 01 '20 at 09:26

0 Answers0