A
A
Andrey Soldatov2014-02-19 08:06:34
JavaScript
Andrey Soldatov, 2014-02-19 08:06:34

How to get the result of an asynchronous function in Javascript?

There is one asynchronous function. that extracts something. This is how it is used:

getSomeItems(
  function( someItems ) { 
    /someItems - полученное(или получаемое?) нечто
    /тут можно сделать что-то с этим нечто
  }
);

What are the ways to return "someItems" ?
It is clear that such a construction will return undefined:
getSomeItems(
  function( someItems ) { 
    return someItems
  }
);

Correct me if the question is incorrect somewhere.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
max7 M7, 2014-02-19
@frumcheg

And the old grandfather way

var mySomeItems = null;
getSomeItems(
  function( someItems ) { 
    mySomeItems = someItems;
  }
);

and somewhere
if(mySomeItems)
{
   ...
}

For example, I use "event emitter" like this:
1. if you can not change the getSomeItems function
var myME = new ManagerEvents(...); // <-- где-то

myME.on("NewSomeItems", function(event)
{
   var someItems = event.data;
   ...
});

getSomeItems(
  (function( someItems ) 
  { 
    this.emit("NewSomeItems", someItems);
  }).bind(myME)
);

2. if you can change the getSomeItems function
var myME = new ManagerEvents(...); // <-- где-то

myME.on("NewSomeItems", function(event)
{
   var someItems = event.data;
   ...
});

getSomeItems(myME); // просто принимает аргументом ManagerEvents и внутри генерирует событие.

Then I added a function to my ManagerEvents (approximately)
ManagerEvents.prototype.delegate = function(name)
{
   var me = this;
   return function()
   {
      return me.emit(name, arguments);
   };
};

and in the end it turns out
var myME = new ManagerEvents(...); // <-- где-то

myME.on("NewSomeItems", function(event)
{
   var someItems = event.data[0];
   ...
});

getSomeItems(myME.delegate("NewSomeItems"));

D
Denis Pushkarev, 2014-02-19
@rock

Just return - no way, for this reason, the callback is passed to it. All subsequent logic will have to be implemented through it.
You can return a Promise .
In the future it will be possible to use generators .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question