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

4
  • 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"); Commented Sep 19, 2019 at 18:20
  • Like this: repl.it/repls/LonelyAcidicWorkplaces Commented Sep 19, 2019 at 18:30
  • @Thom SyntaxError: await is only valid in async function Commented Sep 19, 2019 at 18:33
  • @user3277468 stackoverflow.com/questions/52975133/… Commented Sep 19, 2019 at 19:38

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

do i just call otherMethod() ? in code for x to be defined first then?
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?.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.