Sheba
Sheba

Reputation: 736

importScripts returns undefined in the web workers

For earlier browser versions, Promise is undefined in web workers. So I am using a polyfill Promise by importScripts('Promise.js'), if Promise is undefined. But still I get an undefined object in return.

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();
      ........
}

How can I make this work for web workers?

Upvotes: 4

Views: 1677

Answers (1)

Bergi
Bergi

Reputation: 664247

The importScripts function doesn't return anything. When you access a .Promise property on the call, this will throw, and your code stops executing. Btw, typeof never returns undefined, so you were lucky and it was never exected.

if (typeof Promise !== "function") self.importScripts('./Promise.js');

var promise = new Promise(function (resolve, reject) {
    …
});

Upvotes: 4

Related Questions