Issue
in javascript we can run functions in parallel using promise.all but it doesn't exist in python, how can I run two functions in parallel in python?
import discord
import asyncio
from discord.ext import tasks, commands
client = discord.Client()
client = commands.Bot(command_prefix='!')
@client.event
async def on_ready():
print("Monitor Ativo!")
promise.start()
async def bar():
print("sjj")
async def ba():
print("dhhdh")
@tasks.loop(seconds=5)
async def promise():
await asyncio.wait([bar(), ba()])
But I noticed that when I run the function it always runs the last function first, so it can't be running in parallel right? Since it's always running the last function before the first one, so it has a pattern, and so it can't be running in parallel, how can I run two functions in parallel in python, equivalent to promise.all in javascript.
Solution
You can use asyncio.create_task
.
Code:
import asyncio
import time
async def bar():
await asyncio.sleep(5)
print("sjj")
async def ba():
await asyncio.sleep(3)
print("dhhdh")
async def promise():
tasks = [asyncio.create_task(bar()), asyncio.create_task(ba())]
for task in tasks:
await task
asyncio.run(promise())
Answered By - KetZoomer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.