浏览代码

Add a timeout option to AssetManager.preload()

customisations
alemart 9 个月前
父节点
当前提交
46a0787449
共有 2 个文件被更改,包括 14 次插入5 次删除
  1. 1
    1
      demos/hello-babylon/demo.js
  2. 13
    4
      plugins/extras/asset-manager.js

+ 1
- 1
demos/hello-babylon/demo.js 查看文件

99
             '../assets/cat.glb',
99
             '../assets/cat.glb',
100
             '../assets/magic-circle.png',
100
             '../assets/magic-circle.png',
101
             '../assets/it-works.png',
101
             '../assets/it-works.png',
102
-        ]);
102
+        ], { timeout: 20 });
103
     }
103
     }
104
 
104
 
105
     /**
105
     /**

+ 13
- 4
plugins/extras/asset-manager.js 查看文件

45
     /**
45
     /**
46
      * Preload one or more assets
46
      * Preload one or more assets
47
      * @param {string|string[]} url URL(s) of the asset(s)
47
      * @param {string|string[]} url URL(s) of the asset(s)
48
+     * @param {object} [options]
49
+     * @param {number} [options.timeout] timeout, in seconds
48
      * @returns {Promise<void>}
50
      * @returns {Promise<void>}
49
      */
51
      */
50
-    preload(url)
52
+    preload(url, options = {})
51
     {
53
     {
52
         if(Array.isArray(url))
54
         if(Array.isArray(url))
53
-            return Promise.all(url.map(url => this.preload(url)));
55
+            return Promise.all(url.map(url => this.preload(url, options)));
54
 
56
 
55
         if(typeof url != 'string')
57
         if(typeof url != 'string')
56
             return Promise.reject(new TypeError());
58
             return Promise.reject(new TypeError());
59
         if(this._assetMap.has(filename))
61
         if(this._assetMap.has(filename))
60
             return Promise.resolve();
62
             return Promise.resolve();
61
 
63
 
62
-        return new Promise(resolve => {
64
+        return new Promise((resolve, reject) => {
65
+            const seconds = options.timeout !== undefined ? options.timeout : Infinity;
66
+            const timeoutFn = () => reject(new Error(`Can't preload assets: timeout!`));
67
+            const timeoutId = isFinite(seconds) ? setTimeout(timeoutFn, seconds * 1000) : undefined;
68
+
63
             fetch(url)
69
             fetch(url)
64
             .then(response => {
70
             .then(response => {
65
                 if(!response.ok)
71
                 if(!response.ok)
77
             .catch(error => {
83
             .catch(error => {
78
                 console.warn(`Can't preload asset "${filename}"! ${error.message} (${url})`);
84
                 console.warn(`Can't preload asset "${filename}"! ${error.message} (${url})`);
79
             })
85
             })
80
-            .finally(resolve);
86
+            .finally(() => {
87
+                clearTimeout(timeoutId);
88
+                resolve();
89
+            });
81
         });
90
         });
82
     }
91
     }
83
 
92
 

正在加载...
取消
保存