'Translating a specific Promise from Javascript to Python

I am trying to translate this piece of code from Javascript to Python but could not find an equivalent of a Promise and an async function in Python.

async function sendRequest(options) {
    return new Promise(resolve => {
        request(options, function(error, response, body) {
            if (error) throw new Error(error)
            resolve({
                response: response,
                body: body
            })
        })
    })
} 


Solution 1:[1]

You are looking for python's asyncio. The high-level equivalent of a javascript Promise is an awaitable. Since you want to return an awaitable from a function, you should use the async keyword to return a coroutine, which is a type of awaitable.

As for making an async http request, I would recommend aiohttp.

It sounds like this might be some sort of assignment, so I'm not going to fill in all the blanks for you, but the aiohttp link I provided has plenty of good examples and comprehensive docs that you can dig into. The below is a template for you to work from:

import aiohttp
import asyncio

# this function returns a coroutine, which must be awaited
# elsewhere. you can use return statements normally within its
# body, but be aware that those will be returned from the
# coroutine once it has been awaited, not directly from
# send_request
async def send_request(options):
    # do stuff with aiohttp...

# this is how to call from synchronous code
loop = asyncio.get_event_loop()
loop.run_until_complete(send_request())

# this is how to call from within another async function
async def foo():
    await send_request(options)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1