Quantcast
Viewing latest article 16
Browse Latest Browse All 44

Answer by Pieter Jan Bonestroo for How do I return the response from an asynchronous call?

The question was:

How do I return the response from an asynchronous call?

which can be interpreted as:

How to make asynchronous code look synchronous?

The solution will be to avoid callbacks, and use a combination of Promises and async/await.

I would like to give an example for an Ajax request.

(Although it can be written in JavaScript, I prefer to write it in Python, and compile it to JavaScript using Transcrypt. It will be clear enough.)

Let’s first enable jQuery usage, to have $ available as S:

__pragma__ ('alias', 'S', '$')

Define a function which returns a Promise, in this case an Ajax call:

def read(url: str):    deferred = S.Deferred()    S.ajax({'type': "POST", 'url': url, 'data': { },'success': lambda d: deferred.resolve(d),'error': lambda e: deferred.reject(e)    })    return deferred.promise()

Use the asynchronous code as if it were synchronous:

async def readALot():    try:        result1 = await read("url_1")        result2 = await read("url_2")    except Exception:        console.warn("Reading a lot failed")

Viewing latest article 16
Browse Latest Browse All 44

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>