Asynchronous JS has always been a bit confusing for me...
I have this example code:
function asyncFunction() {
return new Promise(function(resolve, reject) {
resolve([1, 2, 3, 4, 5])
})
};
function example() {
asyncFunction().then(
output => {
for (element of output) {
console.log(element + ", A") //This should be displayed first
}
}
)
};
example();
console.log('B'); //But it isn't
Which produces the following output:
B
1, A
2, A
3, A
4, A
5, A
Is there a way to program this so that B will be printed after the As? I'm actually using an RSS feed parser module here, the above is just an example to illustrate the problem.
Calling asyncFunction
returns a Promise. Even if the Promise resolves immediately, any .then
s chained onto it will be put into the microtask queue, whose tasks will only start running once all other synchronous code has finished.
Since console.log('B');
runs synchronously after the example
call, B
will be printed before the .then
callback runs.
If you want to be sure B gets logged after all array elements are logged, return the asyncFunction
promise from example
, then call .then
on it, and log B
inside that .then
's callback:
function asyncFunction() { return new Promise(function(resolve, reject) { resolve([1, 2, 3, 4, 5]) }) }; function example() { return asyncFunction().then( output => { for (element of output) { console.log(element + ", A") //This should be displayed first } } ) }; example().then(() => { console.log('B'); //But it isn't });
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.