使用Promise顺序加载脚本

时间:2018-09-04 21:03:01

标签: javascript promise here-api

我正在尝试使用Promises加载Here Maps JS脚本。我有三个脚本,后两个脚本依赖于第一个脚本,一旦第一个脚本已加载,便可以异步加载。问题是第一个脚本加载后,它不会等待 then()中的函数:

const libraries = {
    mapsjsCore: 'http://js.api.here.com/v3/3.0/mapsjs-core.js',
    mapsjsService: 'http://js.api.here.com/v3/3.0/mapsjs-service.js',
    mapjsEvents: 'http://js.api.here.com/v3/3.0/mapsjs-mapevents.js'
};

const headTag = document.getElementsByTagName('head')[0];

export const loadMap = function () {

    // First script loads, returns immediately and
    // starts initializing the map without
    // waiting the last two scripts to load ???
    
    return getLibrary(libraries.mapsjsCore)
    .then(() => Promise.all([
    
            // Load the rest async
            getLibrary(libraries.mapsjsService),
            getLibrary(libraries.mapjsEvents)
        ])
    )
    .catch(error => new Error('Unable to load map files'))
}

function getLibrary(url) {
    return new Promise((resolve, reject) => {
        let scriptHTML = document.createElement('script');

        scriptHTML.type = 'text/javascript';
        scriptHTML.charset = 'utf-8';
        scriptHTML.async = true;
        scriptHTML.src = url;

        scriptHTML.onload = function () {
            resolve(url);
        }
        scriptHTML.onerror = function () {
            reject('error')
        }

        headTag.appendChild(scriptHTML);
    })
}

加载顺序似乎还可以:

loading sequence screenshot

那么如何使 loadMap()等待 then()然后返回?即使将 loadMap()包装在Promise中并在 then()之后解析,结果是否相同?我在这里想念什么?

1 个答案:

答案 0 :(得分:1)

根据上面的评论,您似乎已经尝试过:

loadMap().then(initMap());

但是这里的问题是initMap()将立即执行。您应该使用以下语法:

loadMap().then(initMap);

initMap函数仅在映射全部加载完毕后才会执行。

下面是一个完整的工作示例。

const libraries = {
    mapsjsCore: 'http://js.api.here.com/v3/3.0/mapsjs-core.js',
    mapsjsService: 'http://js.api.here.com/v3/3.0/mapsjs-service.js',
    mapjsEvents: 'http://js.api.here.com/v3/3.0/mapsjs-mapevents.js'
};

const headTag = document.getElementsByTagName('head')[0];

const loadMap = function () {

    // First script loads, returns immediately and
    // starts initializing the map without
    // waiting the last two scripts to load ???
    
    return getLibrary(libraries.mapsjsCore)
    .then(() => Promise.all([
    
            // Load the rest async
            getLibrary(libraries.mapsjsService),
            getLibrary(libraries.mapjsEvents)
        ])
    )
    .catch(error => new Error('Unable to load map files'))
}

function getLibrary(url) {
    return new Promise((resolve, reject) => {
        let scriptHTML = document.createElement('script');

        scriptHTML.type = 'text/javascript';
        scriptHTML.charset = 'utf-8';
        scriptHTML.async = true;
        scriptHTML.src = url;

        scriptHTML.onload = function () {
            console.log(`Loaded: ${url}`);
            resolve(url);
        }
        scriptHTML.onerror = function () {
            reject('error')
        }

        headTag.appendChild(scriptHTML);
    })
}

function initMap() {
  console.log(`initMap`);
}

loadMap().then(initMap);
// This prints
//   Loaded: http://js.api.here.com/v3/3.0/mapsjs-core.js
//   Loaded: http://js.api.here.com/v3/3.0/mapsjs-service.js
//   Loaded: http://js.api.here.com/v3/3.0/mapsjs-mapevents.js
//   initMap