0

lately I've had some trouble dealing with asynchronous methods. I've been getting around using setTimeout(); but I know this is neither optimal nor recommended. Any help is greatly appreciated.

I have an asynchronous method inside a function and I want the function to wait until the async method is done to return the value. I have something like this:

    function myFun{
       var myarray = [];

       db.asyncmethod(function (){
          myarray.push("Something");
       });

       return myarray; 
    }

The problem is that myarrayis returned empty because asyncmethod hasn't finished yet. How should I handle this?

Thanks =)

edferda
  • 440
  • 1
  • 5
  • 11
  • Return a promise instead. – zerkms Jul 17 '14 at 23:08
  • You made me promises promises! https://www.youtube.com/watch?v=H8Q83DPZy6E – cgatian Jul 17 '14 at 23:09
  • 1
    What you want to do is impossible. You cannot turn an asynchronous call into a synchronous one in Javascript (and this is basically what you ask for). `myFun` consumes an async method, hence it should be async itself. And the best way to write async code is to use `Promise` as other have pointed out. Learn about it. If you have the luxury of using ES7 (maybe via traceurjs transpiler), using `async/await` is the closest you'll be to a synchronous syntax. – jods Jul 17 '14 at 23:11

0 Answers0