var a = [[1,2,3],[4,5,6],[7,8,9]]
var b = []
const co = require('co');
new Promise(function(resolve, reject) {
a.forEach(function(item) {
item.forEach(function(it) {
setTimeout(function () {
b.push(it)
}, 1000);
})
})
// resolve(b)
}).then(function(data){
console.log(data);
})
// 主要是异步的问题还是怎么的,会直接返回b = [] 而不是期待的
// b = [1,2,3,4,5,6,7,8,9]
The promise changes to the resolve state before the timer is executed, and the then callback is executed and b is output.
Then the timer times out and the data is placed in b.
Resolve should be done after all timers have expired, instead of resolving directly after setting the timer.
This promise has no resolve or reject, so it is always pending and will not console.log. So I guess you forgot to uncomment the resolve line.
Inside your promise are these codes, which traverse the two-dimensional array. For each element of this two-dimensional array, set a timer that adds the element to b after 1 second. After setting the timer, the promise is resolved first. It has not yet reached 1 second, the timer has not been executed yet, and b is still an empty array. And because you resolved, the statement after your then was executed. This is the problem you encountered.
If you wait for a while (after 1 second) and then output a, it will actually be the result you want. After one second, the set timers time out and trigger, and then push elements to b.
The result you want should be written like this?
Judge in each timer, if I am the last one in the two-dimensional array, then I will resolve. That's it.
I feel like the writing is very confusing. Why is there a co but not using it? The Promise is not resolved.
If you want to push an element every 1 second, you can do this.