Reputation: 141
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
Upvotes: 0
Views: 38
Reputation: 134
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?.
Upvotes: 0
Reputation: 2332
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.
Upvotes: 1