0

I met a problem in JS async function. Here is the sample code:

switch (name) {
case "0":
    async_function(1, function() {

    });
    return;
case "1":
    console.log("1");
    return;
}
doSomething();

As you can see, if case "0" run, it is probably code will return before async_function. That is not what I want. Is there any good way to deal with this problem? Thanks!

  • Where did you get your `async_function`? Is it a placeholder for a `setTimeout`? – Zaenille Oct 24 '14 at 04:55
  • 3
    The solution is always the same: If a function performs an async operation, you either have to make it accept a callback or return a promise. See http://stackoverflow.com/q/23667086/218196 and http://stackoverflow.com/q/14220321/218196 for examples. – Felix Kling Oct 24 '14 at 04:56
  • In fact, here I use "chrome.storage.sync.get()" API. – user3770400 Oct 24 '14 at 04:58
  • you might want to change the `return` to `break` inside the `switch` if you want to execute `doSomething`. Also what are you trying to do... do you want to execute doSomething after the async function is executed – Arun P Johny Oct 24 '14 at 05:02
  • a skeleton to the solution could look like http://jsfiddle.net/arunpjohny/mfp7gqhf/1/ – Arun P Johny Oct 24 '14 at 05:07

0 Answers0