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

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

$
0
0

While promises and callbacks work fine in many situations, it is a pain in the rear to express something like:

if (!name) {  name = async1();}async2(name);

You'd end up going through async1; check if name is undefined or not and call the callback accordingly.

async1(name, callback) {  if (name)    callback(name)  else {    doSomething(callback)  }}async1(name, async2)

While it is okay in small examples it gets annoying when you have a lot of similar cases and error handling involved.

Fibers helps in solving the issue.

var Fiber = require('fibers')function async1(container) {  var current = Fiber.current  var result  doSomething(function(name) {    result = name    fiber.run()  })  Fiber.yield()  return result}Fiber(function() {  var name  if (!name) {    name = async1()  }  async2(name)  // Make any number of async calls from here}

You can checkout the project here.


Viewing all articles
Browse latest Browse all 46

Trending Articles



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