I have two function which have different process time, lets say one() takes 1 second, two() takes 0.3 second. I trying to run function one() runs first and then do function two() using promise. in my code i set two() as resolved, but actually its runs function two() before one() finished.
sorry my english not that good, i hope you understand my context here
main();
function main() {
let promise = new Promise(function(resolved) {
one();
resolved();
});
promise.then(two());
}
function one() {
setTimeout(() => {
console.log("ONE");
}, 1000);
}
function two() {
setTimeout(() => {
console.log("TWO");
}, 300);
}
>Solution :
You are running one first, log TWO before ONE is because method one takes more timeout.
You could change function one to an async function, resolve it after the timeout, and let function two wait for its execution to finish.
Option #1: You can use async/await to ensure one is resolved before executing function two.
main();
async function main() {
await one();
two();
}
function one() {
return new Promise(resolve => {
setTimeout(() => {
console.log("ONE");
resolve();
}, 1000);
});
}
function two() {
setTimeout(() => {
console.log("TWO");
}, 300);
}
Option #2: Use promise.then
main();
function main() {
one().then(two);
}
function one() {
return new Promise(resolve => {
setTimeout(() => {
console.log("ONE");
resolve();
}, 1000);
});
}
function two() {
setTimeout(() => {
console.log("TWO");
}, 300);
}