0

I have a method that I want to finish before any code after it can be ran but am lost in understand external links when is comes to this.

In one method I have the following code

var x = someMethod("1","2","3"); // Finish before anything below can be ran

The method itself is simple

function someMethod(x,y,z){
    if(1){
        return "sdfh"
    } else if(2){
        return "asdf"
    } else {
        return "ljkk"
    }
}

How can I retrieve x before continue the code below it. Ive seen examples of nested functions, await, async but am lost

Thom
  • 1,473
  • 2
  • 20
  • 30
user3277468
  • 141
  • 2
  • 11
  • In your case `someMethod` is synchronous so your code is correct. But if `someMethod` was asynchronous hits signature would be `async function someMethod(x,y,z)` and the call to it be `var x = await someMethod("1","2","3");` – Thom Sep 19 '19 at 18:20
  • Like this: https://repl.it/repls/LonelyAcidicWorkplaces – Shumail Sep 19 '19 at 18:30
  • @Thom SyntaxError: await is only valid in async function – user3277468 Sep 19 '19 at 18:33
  • @user3277468 https://stackoverflow.com/questions/52975133/javascript-syntaxerror-await-is-only-valid-in-async-function – Thom Sep 19 '19 at 19:38

2 Answers2

1

Try:

const someMethod = (x, y, z) => {
  ...
};

const otherMethod = async () => {
  let x = 'before value';
  console.log(`before someMethod x: ${x}`);
  // Finish before anything below can be ran
  x = await someMethod("1", "2", "3"); 
  console.log(`after someMethod x: ${x}`);
};

Basically you are defining the function which has the await call as an asynchronous function using the async keyword in the function declaration - and can signify the portion of the code which you would like to wait by prepending with await. There are nuances to this - but hopefully this helps.

dyouberg
  • 2,206
  • 1
  • 11
  • 21
0

Java script is single thread and synchronous. I recommend checking out JavaScript promises. However I would assume your code executes synchronously until it hits something like a AJAX that is asynchronous. check this answer out: When is JavaScript synchronous?.