I’m new to javascript and promises. I’m trying to get one function not to start running until the first function has completed.
In this case, I want the "dontDoUntilDelayIsComplete" function to run AFTER the "delayGreet" function.
function delayGreet() {
setTimeout(greet, 1000);
}
function greet() {
para1.textContent = "Hi there!";
}
function createPromise() {
return new Promise((resolve) => resolve(delayGreet));
}
function dontDoUntilDelayIsComplete() {
para2.textContent = "Please dont do before";
}
function callMethod() {
createPromise().then(dontDoUntilDelayIsComplete);
}
callMethod();`
I’ve tried putting the functions within a promise and use the .then() method. However, I’m unable to get it to work.
2
Answers
.then takes a callback function with the result (resolve of promise) as a paramater
I don’t think this is accurate:
"I want the "dontDoUntilDelayIsComplete" function to run AFTER the "delayGreet" function"
I think you want
dontDoUntilDelayIsComplete
to run aftergreet
, which is different.setTimeout
does not create a promise, it simply schedules a function to run. If you want something to run immediately after that, then schedule that as well.Here’s a solution with a generic callback:
And here’s one with a promise: