importScripts在web工作程序中返回未定义的

importScripts returns undefined in the web workers

本文关键字:返回 未定义 工作程序 web importScripts      更新时间:2023-09-26

对于早期的浏览器版本,Promise在web Worker中是未定义的。因此,如果Promise未定义,我将使用importScripts的polyfill Promise('Promise.js')。但我仍然得到了一个未定义的对象作为回报。

var promise;
if(typeof Promise === undefined) {
  self.importScripts('./Promise.js').Promise;
}
promise = new Promise(function (resolve, reject) {
  var url = ajaxArgs.url || '',
      data = ajaxArgs.data || {},
      type = ajaxArgs.method || 'GET',
      isGet = type === 'GET',
      request = new XMLHttpRequest();
      ........
}

我如何使这项工作为网络工作者?

importScripts函数不返回任何内容。当您在调用中访问.Promise属性时,这将引发,并且您的代码将停止执行。顺便说一句,typeof从不返回undefined,所以你很幸运,它从未被执行过。

if (typeof Promise !== "function") self.importScripts('./Promise.js');
var promise = new Promise(function (resolve, reject) {
    …
});