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

Answer by Francisco Carmona for How do I return the response from an asynchronous call?

$
0
0

Have a look at this example:

var app = angular.module('plunker', []);app.controller('MainCtrl', function($scope,$http) {    var getJoke = function(){        return $http.get('http://api.icndb.com/jokes/random').then(function(res){            return res.data.value;          });    }    getJoke().then(function(res) {        console.log(res.joke);    });});

As you can see getJoke is returning a resolved promise (it is resolved when returning res.data.value). So you wait until the $http.get request is completed and then console.log(res.joke) is executed (as a normal asynchronous flow).

This is the plnkr:

http://embed.plnkr.co/XlNR7HpCaIhJxskMJfSg/

ES6 way (async - await)

(function(){  async function getJoke(){    let response = await fetch('http://api.icndb.com/jokes/random');    let data = await response.json();    return data.value;  }  getJoke().then((joke) => {    console.log(joke);  });})();

Viewing all articles
Browse latest Browse all 46

Trending Articles



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