javascript async填充数组

时间:2016-11-28 22:52:32

标签: javascript asynchronous

我想了解如何编写自己的异步函数。

那么我如何使用 async 的大量元素填充数组,并立即查看'完成' 行,而不是等待人口完成?

以下是我尝试实现Promises和回调但未成功的示例。

myElement.style.height = '40px'; // for example
// ...
console.log(myElement.clientHeight); // This logs "40". This is not the value I want.
myElement.style.height = 'initial';
console.log(myElement.clientHeight); // This logs the value I want. But I don't want to execute above statement AT ALL!

1 个答案:

答案 0 :(得分:3)

您可以使用Promise对象或只使用setTimeout()

let arr = [];
populateAsync(arr);
console.log('finish');

function populateAsync(arr) {
    setTimeout(function(){
        //do something
    },0)
} 

与Promise

let arr = [];
populateAsync(arr).then(function(){//do something with arr
});
console.log('finish');

function populateAsync(arr) {
    return new Promise(function(resolve, reject){
        //do something
        resolve(arr); //resolve with value
    });
}