I am trying to run through a for loop asynchronously in Python like you can do in Javascript using the map method and promise.all. I have searched everywhere on how to do this, but the code below is still running synchronously (doing one by one, instead of letting the loop do other iterations while it is finishing off the previous like promise.all allows you). Any help would be appreciated.
from jwt import scopes
from googleapiclient.discovery import build
from google.oauth2 import service_account
import json
import asyncio
key = 'file.json'
ID = 'ID'
rg = 'A1'
j2 = service_account.Credentials.from_service_account_file(key, scopes=scopes).with_subject('me@emial.com')
ar = []
cl = build('classroom', 'v1', credentials=j2)
def cour():
co = []
result1 = cl.courses().list().execute()
courses = result1.get('courses', [])
for cc in courses:
co.append(cc['id'])
return co
cco = cour()
async def main():
async def subs2(i):
await asyncio.sleep(0)
result2 = cl.courses().courseWork().list(courseId=i).execute()
works = result2.get('courseWork', [])
for work in works:
result = cl.courses().courseWork().studentSubmissions().list(courseId=work['courseId'], courseWorkId=work['id']).execute()
subs = result.get('studentSubmissions', [])
for sub in subs:
try:
ar.append(sub['assignedGrade'])
ar.append(sub['courseId'])
ar.append(sub['courseWorkId'])
ar.append(sub['userId'])
except KeyError as name:
pass
coros = [subs2(i) for i in cco]
await asyncio.gather(*coros)
if __name__ == '__main__':
cour()
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()