簡體   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