0

I am trying to set a global variable within a function, but the code continues before the variable has been updated. e.g.

        var username = 'Example';
	const fetch = require('node-fetch');
	var num = 1234;
	var uuidP;
	const request = async () => {
		const response = await fetch(`https://api.mojang.com/users/profiles/minecraft/${username}`);
		const json = await response.json();
		uuidP = json.id;
	}
	request();

	console.log(num); //returns 1234
	console.log(uuidP); //returns udefined

10
  • This is simply false. Commented Oct 17, 2019 at 1:54
  • Possible duplicate of How can I make a program wait for a variable change in javascript? Commented Oct 17, 2019 at 1:54
  • Where is the function call ? Commented Oct 17, 2019 at 1:54
  • 1
    You didn't call the function update() Commented Oct 17, 2019 at 1:56
  • ASDFGerte well this is the cause of an error for me. Commented Oct 17, 2019 at 1:58

1 Answer 1

1

Javascript is heavily optimised. You need to declare the update() function is asynchronous, and then use a Promise to await the response of the update. Have a look at this example.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.