How to use Python asyncio tasks in for-loop?

Viewed 34

What changes shoud I make to run this code asynchronously? Function func2() takes a long time to complete. The goal is not to wait until it ends but to start a new iteration and save time.

import asyncio
import requests

comb_list = [[{'value1'}, {'value2'}], [{'value3'}, {'value4'}], [{'value5'}, {'value6'}], [{'value7'}, {'value8'}]]

async def func2(i, j):
    r = requests.get('https://...', params={'i': 'i', 'j': 'j'})
    r.json()  # I receive 'i2' and 'j2'
    r2 = requests.get('https://...', params={'i2': 'i2', 'j2': 'j2'})
    r2.json()  # I receive 'i3' and 'j3'
    r3 = requests.get('https://...', params={'i3': 'i3', 'j3': 'j3'})
    r3.json()  # I receive 'i4' and 'j4'

async def func1(comb_list):
    tasks = []
    comb_num = 0
    for i in range(len(comb_list)):
        task = asyncio.create_task(func2(comb_list[comb_num][0], comb_list[comb_num][1]))
        tasks.append(task)
        comb_num += 1
    await asyncio.gather(*tasks)

def main():
    asyncio.run(func1(comb_list))

if __name__ == '__main__':
    main()
0 Answers
Related