Edaz
Edaz

Reputation: 300

javascript wait for function to finish execution before continuing

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

Upvotes: 0

Views: 12398

Answers (1)

Paul
Paul

Reputation: 32

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.

Upvotes: 1

Related Questions