繁体   English   中英

使用Promise顺序加载脚本

[英]Sequential Script Loading using Promises

我正在尝试使用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); }) } 

加载顺序似乎还可以:

加载序列截图

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

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

loadMap().then(initMap());

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

loadMap().then(initMap);

仅在所有地图都加载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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM