I have a function that returns Promise
let processWork = function () {
return new Promise(resolve => {
console.log('- internal: start')
// just wait 200ms for example
let future = new Date(new Date().getTime() + 200)
while (future > new Date()) {}
console.log('- internal: done')
resolve()
})
}
I call it and use then
function to change variable to break endless while but not work
let doing = false
let done = false
while (!done) {
if (doing) {
continue
}
console.log('Starting work')
doing = true
processWork()
.then(() => {
console.log('Finished')
done = true
})
}
I get output
Starting work
- internal: start
- internal: done
and my code's still running forever. My question is why then function
not running in this case.
It is not true that a promise will somehow get resolved while a busy loop is being executed. As long as a loop is executing no other JavaScript will execute (excluding web workers). The following loop will always execute the continue
statement in every iteration and will never finish.
let doing = false
let done = false
while (!done) {
if (doing) {
continue
}
// ...
}
No promise could help interrupt this loop, but in your case, there is not even a promise since processWork never gets executed.
If processWork would get executed, the loop in the promise constructor callback will lock up the browser until the target time arrives: no other JavaScript gets executed during that delay. This defeats the purpose of promises: they are intended not to lock up the browser and allow the execution of other code while the promise is still pending.
So, do it like this:
let processWork = function () { return new Promise(resolve => { console.log('- internal: start delay of 200ms') // just wait 200ms for example, but don't stop execution of other code setTimeout(resolve, 200); }) } console.log('Starting work') processWork().then(() => { console.log('Promise resolved. Finished'); }); console.log('Waiting for promise to resolve...'); console.log('In the meanwhile let\\'s calculate 10!'); let fact = 1; for (let i = 1; i <= 10; i++) { fact *= i; } console.log('10! = ', fact);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.