can someone try to fix my problem?
I am trying to get this output:
100x do C
done B
done A
But everytime i get this one:
10x do C
done B
done A
Is it possible to get it without using async/await feature?
function a() {
let myPromise = new Promise(function(myResolve, myReject) {
b();
myResolve()
});
myPromise.then(function() {
console.log('done A')
});
}
function b() {
let myPromise = new Promise(function(myResolve, myReject) {
for (i = 0; i < 10; i++) {
c();
}
myResolve()
});
myPromise.then(function() {
console.log('done B')
});
}
function c() {
for (i = 0; i < 10; i++) {
console.log('do C')
}
}
a()
The problem is that you’re not declaring
i
, so you’re creating an implicit global variable that bothb
andc
write to. (I wrote an article about these years ago: The Horror of Implicit Globals.)In the below, I’m going to make it three runs of three instead of ten runs of ten, just so we can see it more clearly (and so I don’t have to increase the size of the in-snippet console’s history — it has an option for that, but I don’t recall the details).
I strongly recommend using strict mode so that this is the error it always should have been. Here’s your code in strict mode and with rejection handlers added:
If you declare
i
(in both places), you’ll get the result you expect.but, beware that the reason you’re getting the output you’re getting is that everything except the calls to the fulfillment handlers is synchronous. If instead of a
for
loop you were doing some asynchronous process, there’s nothing preventing you from gettingdone B
ordone A
before all of the work done byc
is done, because there’s nothing connecting those promises together.Let’s see that. Suppose we have an asynchronous version of
console.log
that waits 10ms before writing the log entry (but we’ll useconsole.log
to write outdone A
anddone B
immediately, so you can see when they ran):Let’s look at what happens:
Notice how things aren’t connected to each other.
To connect them, you’d have to make
b
wait forc
‘s promise to be fulfilled, and makea
wait forb
‘s promise to be fulfilled. Something like this: