常规方法

代码如下面demo所示,在foreach的回调函数中进行判断,当循环到数组最后一位元素的时候,执行回调函数:

function callBack(){console.log('all done');}function f(){var count = 0;var arrTemp = [1, 2, 3];arrTemp.forEach((item, index, arr) => {count++;if(count === arr.length){this.callBack();}})}f()

使用Promise实现

实际工作中,当目标数组的元素内容比较复杂,在回调函数中没有办法进行简单的逻辑判断时,可以使用Promise.all 方法实现:

Promise.all([1,2,3].map((item) => {return new Promise((resolve, reject) => {setTimeout(() => {console.log("in async function, item is" + item);resolve(item)},Math.random()*2000)})})).then((result) => {console.log("all done");console.log("result are:", result);})