I am not able to understand grasp the process of sequentially running functions in JavaScript. I read many posts on this topic on stackoverflow, but they did not enlight me. Let us assume that we have two function fastFunction() and slowFunction(). When I run them one after the other JavaScript will not run them sequentially.
function fastFunction() {
console.log('fast function!');
}
function slowFunction() {
setTimeout(() => {console.log('slowFunction!')}, 1000);
}
slowFunction();
fastFunction();
I tried to use callbacks, promises and async/await syntax (see next example), but I am not able to get JavaScript to run these functions in sequential order. To be quite honest I still wonder why such a fundamental problem is that difficult to solve in JavaScript :D!
function fastFunction() {
console.log('fast function!');
}
async function slowFunction() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => {console.log('slowFunction!')}, 1000)});
let result = await promise;
}
slowFunction().then(fastFunction())
I would be glad if anyone could explain me what I am doing wrong.
Edit: After suggestion of passing fastFunction() as callback (not sure if that is what the comment was suggesting), does not solve the problem.
function fastFunction() {
console.log('fast function!');
}
function slowFunction(callback) {
setTimeout(() => {
console.log('slowFunction!');
callback();
}, 10000);
}
slowFunction(fastFunction);