如何在javascript中异步声明变量?

时间:2017-12-02 06:36:15

标签: javascript promise firefox-webextensions

所以我在JavaScript中加入了一堆非常大的列表,我在webextension中加载。不幸的是,它们太大了,它们减慢了页面加载速度,每个列表大约5毫秒。虽然很小,但我希望在加载时摆脱这个时间并在承诺中异步加载变量以便以后使用它们。

1 个答案:

答案 0 :(得分:0)

事实证明,Promises有一个方法可以从任何对象Promise.resolve()创建一个Promise。例如,对于我非常大的列表,我们假设我有三个函数,名为createList1,createList2和createList3,它们创建并返回一个非常大的列表。然后,我可以异步创建这些列表,聚合它们,并在调用方法后通过以下方式使用它们:

// use a closure for good practice.
let closure = (function() {
    // create the promises when the script is loaded
    var x = Promise.resolve(createList1());
    var y = Promise.resolve(createList2());
    var z = Promise.resolve(createList3());
    // aggregate all promises into one promise
    return Promise.all([x,y,z]);
})();

function doSomething(listOfLargeLists) {
    // given the list very large lists, do something with each of them
    // do stuff here, e.g. var actualList1 = listOfLargeLists[0];
}

closure.then((listOfLargeLists) => {
    doSomething(listOfLargeLists);
});

如果你只是想异步声明一个变量,你只需要在一个promise中创建它,然后每当你想使用它时,使用then:

var x = Promise.resolve(createList1());

function doSomething(bigList) {
    // do something with the list
}

function doSomethingDifferent(bigList) {
    // do something different with the list
}

var y = x.then((bigList) => {
    doSomething(bigList);
});

// Async with y
var z = x.then((bigList) => {
    doSomethingDifferent(bigList);
});

// Or Wait for y first and use its return value
var yUpdate = y.then((bigList) => {
    doSomethingDifferent(bigList);
});