Quantcast
Channel: How do I return the response from an asynchronous call? - Stack Overflow
Viewing all articles
Browse latest Browse all 44

Answer by Kamil Kiełczewski for How do I return the response from an asynchronous call?

$
0
0

Await

A request works in an asynchronous way, so you can't read the data synchronously as in typical code. However, using async/await you can create asynchronous code which looks close/similar to the usual synchronous/sequential style. Code which processes response data needs to be wrapped by an async function (load in the below snippet) and inside it you need to add the await keyword before foo() (which also uses async/await).

async function foo() {  var url = 'https://jsonplaceholder.typicode.com/todos/1';  var result = (await fetch(url)).text(); // Or .json()  return result;}async function load() {  var result = await foo();  console.log(result);}load();

Remember that an async function always (implicitly) wraps its result into a promise (so it returns a promise).


Viewing all articles
Browse latest Browse all 44

Trending Articles