Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

operative

Package Overview
Dependencies
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

operative - npm Package Compare versions

Comparing version 0.0.3 to 0.1.0

test/demos/promises.html

164

dist/operative.js

@@ -9,6 +9,8 @@ /**

* @version 0.0.2
* @contributors
* James Padolsey
*/
(function() {
if (typeof window == 'undefined' && self.importScripts) {
if (typeof window == 'undefined' && self.importScripts) {
// I'm a worker! Run the boiler-script:

@@ -56,4 +58,11 @@ // (Operative itself is called in IE10 as a worker, to avoid SecurityErrors)

operative.Promise = window.Promise;
// Expose:
window.operative = operative;
if (typeof module !== 'undefined' && module.exports) {
module.exports = operative;
} else {
window.operative = operative;
}

@@ -72,2 +81,10 @@ operative.setSelfURL = function(url) {

if (typeof module == 'function') {
// Allow a single function to be passed.
var o = new Operative({ main: module });
return function() {
return o.main.apply(o, arguments);
};
}
module.get = module.get || function(prop) {

@@ -92,2 +109,3 @@ return this[prop];

this.callbacks = {};
this.deferreds = {};

@@ -128,3 +146,3 @@ if (operative.hasWorkerSupport) {

if (typeof property == 'function') {
script.push(' self["' + i.replace(/"/g, '\\"') + '"] = ' + property.toString() + ';');
script.push(' self["' + i.replace(/"/g, '\\"') + '"] = ' + property.toString() + ';');
} else {

@@ -154,3 +172,3 @@ dataProperties[i] = property;

return;
}

@@ -161,13 +179,21 @@

switch (data.cmd) {
case 'console':
case 'console':
window.console && window.console[data.method].apply(window.console, data.args);
break;
case 'result':
if (data.token in this.callbacks) {
var cb = this.callbacks[data.token];
delete this.callbacks[data.token];
cb(data.result);
} else {
throw new Error('Operative: Unmatched token: ' + data.token);
var callback = this.callbacks[data.token];
var deferred = this.deferreds[data.token];
delete this.callbacks[data.token];
delete this.deferreds[data.token];
var deferredAction = data.result && data.result.isDeferred && data.result.action;
if (deferred && deferredAction) {
deferred[deferredAction](data.result.arg);
} else if (callback) {
callback(data.result);
}
break;

@@ -224,3 +250,3 @@ }

});
this._postWorkerMessage({

@@ -244,6 +270,9 @@ definitions: this.dataProperties

var args = slice.call(arguments);
var cb = args.pop();
var cb = typeof args[args.length - 1] == 'function' && args.pop();
if (typeof cb != 'function') {
throw new TypeError('Operative: Expected last argument to be Function (callback)');
if (!cb && !operative.Promise) {
throw new Error(
'Operative: No callback has been passed. Assumed that you want a promise. ' +
'But `operative.Promise` is null. Please provide Promise polyfill/lib.'
);
}

@@ -253,32 +282,59 @@

_self._postWorkerMessage({
method: methodName,
args: args,
token: token
});
if (cb) {
_self.callbacks[token] = cb;
sendToWorker();
} else if (operative.Promise) {
return new operative.Promise(function(deferred) {
_self.deferreds[token] = deferred;
sendToWorker();
});
}
_self.callbacks[token] = cb;
} else {
setTimeout(function() {
if (cb) {
setTimeout(function() {
runInline();
}, 1);
} else if (operative.Promise) {
return new operative.Promise(function(deferred) {
deferred.fulfil = deferred.fulfill;
setTimeout(function() {
runInline(deferred);
}, 1);
});
}
}
var isAsync = false;
function runInline(deferred) {
_self.module.async = function() {
isAsync = true;
return cb;
};
var isAsync = false;
var result = _self.module[methodName].apply(_self.module, args);
_self.module.async = function() {
isAsync = true;
return cb;
};
_self.module.async = function() {
throw new Error('Operative: async() called at odd time');
};
_self.module.deferred = function() {
return deferred;
};
if (!isAsync) {
cb(result);
}
var result = _self.module[methodName].apply(_self.module, args);
}, 1);
_self.module.async = function() {
throw new Error('Operative: async() called at odd time');
};
if (!isAsync && !deferred) {
cb(result);
}
}
function sendToWorker() {
_self._postWorkerMessage({
method: methodName,
args: args,
token: token
});
}
};

@@ -380,18 +436,43 @@

var isAsync = false;
var isDeferred = false;
self.async = function() {
isAsync = true;
return function(r) {
returnResult(r);
};
return function(r) { returnResult(r); };
};
self.deferred = function() {
isDeferred = true;
var def = {};
function fulfill(r) {
returnResult({
isDeferred: true,
action: 'fulfill',
arg: r
});
return def;
}
function reject(r) {
returnResult({
isDeferred: true,
action: 'reject',
arg: r
});
}
def.fulfil = def.fulfill = fulfill;
def.reject = reject;
return def;
};
var result = self[data.method].apply(self, data.args);
// Clear so it's not accidentally used by other code
// Clear async/deferred so they're not accidentally used by other code
self.async = function() {
throw new Error('Operative: async() called at odd time');
};
self.deferred = function() {
throw new Error('Operative: deferred() called at odd time');
};
if (!isAsync) {
if (!isAsync && !isDeferred) {
returnResult(result);

@@ -411,2 +492,1 @@ }

}());

@@ -1,2 +0,2 @@

/** Operative v0.0.3 (c) 2013 James padolsey, MIT-licensed, http://github.com/padolsey/operative **/
(function(){function makeBlobURI(e){var t;try{t=new Blob([e],{type:"text/javascript"})}catch(r){t=new BlobBuilder,t.append(e),t=t.getBlob()}return URL.createObjectURL(t)}function Operative(e){var t=this;e.get=e.get||function(e){return this[e]},e.set=e.set||function(e,t){return this[e]=t},this._msgQueue=[],this._curToken=0,this.isDestroyed=!1,this.workerIsReady=!1,this.module=e,this.dataProperties={},this.api={},this.callbacks={},operative.hasWorkerSupport?this._setupWorker():this._setupFallback();for(var r in e)hasOwn.call(e,r)&&this._createExposedMethod(r);return this.api.__operative__=this,this.api.destroy=function(){return t.destroy()},this.api}function operative(e){return new Operative(e)}function workerBoilerScript(){var postMessage=self.postMessage,objectTransferSupport=null;self.console={},self.isWorker=!0,["log","debug","error","info","warn","time","timeEnd"].forEach(function(e){self.console[e]=function(){postMessage({cmd:"console",method:e,args:[].slice.call(arguments)})}}),self.addEventListener("message",function(e){function returnResult(e){postMessage({cmd:"result",token:data.token,result:e})}var data=e.data;if("string"==typeof data&&0===data.indexOf("EVAL|"))return eval(data.substring(5)),void 0;if(null==objectTransferSupport)return objectTransferSupport="PING"===e.data[0],self.postMessage(objectTransferSupport?"pingback:objectTransferSupport=YES":"pingback:objectTransferSupport=NO"),objectTransferSupport||(postMessage=function(e){return self.postMessage(JSON.stringify(e))}),void 0;objectTransferSupport||(data=JSON.parse(data));var defs=data.definitions;if(defs){for(var i in defs)self[i]=defs[i];return self.setup&&self.setup(),void 0}var isAsync=!1;self.async=function(){return isAsync=!0,function(e){returnResult(e)}};var result=self[data.method].apply(self,data.args);self.async=function(){throw Error("Operative: async() called at odd time")},isAsync||returnResult(result)})}if("undefined"==typeof window&&self.importScripts)return workerBoilerScript(),void 0;var slice=[].slice,hasOwn={}.hasOwnProperty,scripts=document.getElementsByTagName("script"),opScript=scripts[scripts.length-1],opScriptURL=/operative/.test(opScript.src)&&opScript.src,URL=window.URL||window.webkitURL,BlobBuilder=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder,workerViaBlobSupport=function(){try{new Worker(makeBlobURI(";"))}catch(e){return!1}return!0}();operative.hasWorkerSupport=!!window.Worker,window.operative=operative,operative.setSelfURL=function(e){opScriptURL=e},Operative.prototype={_buildWorkerScript:function(e){var t,r=[],s=this.module,o=this.dataProperties;for(var i in s){var t=s[i];"function"==typeof t?r.push(' self["'+i.replace(/"/g,'\\"')+'"] = '+(""+t)+";"):o[i]=t}return r.join("\n")+(e?"\n("+(""+workerBoilerScript)+"());":"")},_onWorkerMessage:function(e){var t=e.data;if("string"==typeof t&&0===t.indexOf("pingback"))return"pingback:objectTransferSupport=NO"===t&&(this._marshal=function(e){return JSON.stringify(e)},this._demarshal=function(e){return JSON.parse(e)}),this.workerIsReady=!0,this._postQueudMessages(),void 0;switch(t=this._demarshal(t),t.cmd){case"console":window.console&&window.console[t.method].apply(window.console,t.args);break;case"result":if(!(t.token in this.callbacks))throw Error("Operative: Unmatched token: "+t.token);var r=this.callbacks[t.token];delete this.callbacks[t.token],r(t.result)}},_marshal:function(e){return e},_demarshal:function(e){return e},_postWorkerMessage:function(e){return this.workerIsReady?this.worker.postMessage(this._marshal(e)):(this._msgQueue.push(e),void 0)},_postQueudMessages:function(){for(var e=this._msgQueue,t=0,r=e.length;r>t;++t)this._postWorkerMessage(e[t]);this._msgQueue=null},_setupWorker:function(){var e,t=this;if(workerViaBlobSupport)e=this.worker=new Worker(makeBlobURI(this._buildWorkerScript(!0)));else{if(!opScriptURL)throw Error("Operaritve: No operative.js URL available. Please set via operative.setSelfURL(...)");e=this.worker=new Worker(opScriptURL),e.postMessage("EVAL|"+this._buildWorkerScript(!1))}e.postMessage(["PING"]),e.addEventListener("message",function(e){t._onWorkerMessage(e)}),this._postWorkerMessage({definitions:this.dataProperties})},_createExposedMethod:function(e){var t=this;this.api[e]=function(){if(t.isDestroyed)throw Error("Operative: Cannot run method. Operative has already been destroyed");var r=++t._curToken,s=slice.call(arguments),o=s.pop();if("function"!=typeof o)throw new TypeError("Operative: Expected last argument to be Function (callback)");operative.hasWorkerSupport?(t._postWorkerMessage({method:e,args:s,token:r}),t.callbacks[r]=o):setTimeout(function(){var r=!1;t.module.async=function(){return r=!0,o};var i=t.module[e].apply(t.module,s);t.module.async=function(){throw Error("Operative: async() called at odd time")},r||o(i)},1)}},_setupFallback:function(){this.module.isWorker=!1,this.module.setup&&this.module.setup()},destroy:function(){this.isDestroyed=!0,this.worker&&this.worker.terminate()}},operative.Operative=Operative})();
/** Operative v0.1.0 (c) 2013 James padolsey, MIT-licensed, http://github.com/padolsey/operative **/
(function(){function makeBlobURI(e){var r;try{r=new Blob([e],{type:"text/javascript"})}catch(t){r=new BlobBuilder,r.append(e),r=r.getBlob()}return URL.createObjectURL(r)}function Operative(e){var r=this;if("function"==typeof e){var t=new Operative({main:e});return function(){return t.main.apply(t,arguments)}}e.get=e.get||function(e){return this[e]},e.set=e.set||function(e,r){return this[e]=r},this._msgQueue=[],this._curToken=0,this.isDestroyed=!1,this.workerIsReady=!1,this.module=e,this.dataProperties={},this.api={},this.callbacks={},this.deferreds={},operative.hasWorkerSupport?this._setupWorker():this._setupFallback();for(var s in e)hasOwn.call(e,s)&&this._createExposedMethod(s);return this.api.__operative__=this,this.api.destroy=function(){return r.destroy()},this.api}function operative(e){return new Operative(e)}function workerBoilerScript(){var postMessage=self.postMessage,objectTransferSupport=null;self.console={},self.isWorker=!0,["log","debug","error","info","warn","time","timeEnd"].forEach(function(e){self.console[e]=function(){postMessage({cmd:"console",method:e,args:[].slice.call(arguments)})}}),self.addEventListener("message",function(e){function returnResult(e){postMessage({cmd:"result",token:data.token,result:e})}var data=e.data;if("string"==typeof data&&0===data.indexOf("EVAL|"))return eval(data.substring(5)),void 0;if(null==objectTransferSupport)return objectTransferSupport="PING"===e.data[0],self.postMessage(objectTransferSupport?"pingback:objectTransferSupport=YES":"pingback:objectTransferSupport=NO"),objectTransferSupport||(postMessage=function(e){return self.postMessage(JSON.stringify(e))}),void 0;objectTransferSupport||(data=JSON.parse(data));var defs=data.definitions;if(defs){for(var i in defs)self[i]=defs[i];return self.setup&&self.setup(),void 0}var isAsync=!1,isDeferred=!1;self.async=function(){return isAsync=!0,function(e){returnResult(e)}},self.deferred=function(){function e(e){return returnResult({isDeferred:!0,action:"fulfill",arg:e}),t}function r(e){returnResult({isDeferred:!0,action:"reject",arg:e})}isDeferred=!0;var t={};return t.fulfil=t.fulfill=e,t.reject=r,t};var result=self[data.method].apply(self,data.args);self.async=function(){throw Error("Operative: async() called at odd time")},self.deferred=function(){throw Error("Operative: deferred() called at odd time")},isAsync||isDeferred||returnResult(result)})}if("undefined"==typeof window&&self.importScripts)return workerBoilerScript(),void 0;var slice=[].slice,hasOwn={}.hasOwnProperty,scripts=document.getElementsByTagName("script"),opScript=scripts[scripts.length-1],opScriptURL=/operative/.test(opScript.src)&&opScript.src,URL=window.URL||window.webkitURL,BlobBuilder=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder,workerViaBlobSupport=function(){try{new Worker(makeBlobURI(";"))}catch(e){return!1}return!0}();operative.hasWorkerSupport=!!window.Worker,operative.Promise=window.Promise,"undefined"!=typeof module&&module.exports?module.exports=operative:window.operative=operative,operative.setSelfURL=function(e){opScriptURL=e},Operative.prototype={_buildWorkerScript:function(e){var r,t=[],s=this.module,o=this.dataProperties;for(var i in s){var r=s[i];"function"==typeof r?t.push(' self["'+i.replace(/"/g,'\\"')+'"] = '+(""+r)+";"):o[i]=r}return t.join("\n")+(e?"\n("+(""+workerBoilerScript)+"());":"")},_onWorkerMessage:function(e){var r=e.data;if("string"==typeof r&&0===r.indexOf("pingback"))return"pingback:objectTransferSupport=NO"===r&&(this._marshal=function(e){return JSON.stringify(e)},this._demarshal=function(e){return JSON.parse(e)}),this.workerIsReady=!0,this._postQueudMessages(),void 0;switch(r=this._demarshal(r),r.cmd){case"console":window.console&&window.console[r.method].apply(window.console,r.args);break;case"result":var t=this.callbacks[r.token],s=this.deferreds[r.token];delete this.callbacks[r.token],delete this.deferreds[r.token];var o=r.result&&r.result.isDeferred&&r.result.action;s&&o?s[o](r.result.arg):t&&t(r.result)}},_marshal:function(e){return e},_demarshal:function(e){return e},_postWorkerMessage:function(e){return this.workerIsReady?this.worker.postMessage(this._marshal(e)):(this._msgQueue.push(e),void 0)},_postQueudMessages:function(){for(var e=this._msgQueue,r=0,t=e.length;t>r;++r)this._postWorkerMessage(e[r]);this._msgQueue=null},_setupWorker:function(){var e,r=this;if(workerViaBlobSupport)e=this.worker=new Worker(makeBlobURI(this._buildWorkerScript(!0)));else{if(!opScriptURL)throw Error("Operaritve: No operative.js URL available. Please set via operative.setSelfURL(...)");e=this.worker=new Worker(opScriptURL),e.postMessage("EVAL|"+this._buildWorkerScript(!1))}e.postMessage(["PING"]),e.addEventListener("message",function(e){r._onWorkerMessage(e)}),this._postWorkerMessage({definitions:this.dataProperties})},_createExposedMethod:function(e){var r=this;this.api[e]=function(){function t(t){var s=!1;r.module.async=function(){return s=!0,n},r.module.deferred=function(){return t};var o=r.module[e].apply(r.module,i);r.module.async=function(){throw Error("Operative: async() called at odd time")},s||t||n(o)}function s(){r._postWorkerMessage({method:e,args:i,token:o})}if(r.isDestroyed)throw Error("Operative: Cannot run method. Operative has already been destroyed");var o=++r._curToken,i=slice.call(arguments),n="function"==typeof i[i.length-1]&&i.pop();if(!n&&!operative.Promise)throw Error("Operative: No callback has been passed. Assumed that you want a promise. But `operative.Promise` is null. Please provide Promise polyfill/lib.");if(operative.hasWorkerSupport){if(n)r.callbacks[o]=n,s();else if(operative.Promise)return new operative.Promise(function(e){r.deferreds[o]=e,s()})}else if(n)setTimeout(function(){t()},1);else if(operative.Promise)return new operative.Promise(function(e){e.fulfil=e.fulfill,setTimeout(function(){t(e)},1)})}},_setupFallback:function(){this.module.isWorker=!1,this.module.setup&&this.module.setup()},destroy:function(){this.isDestroyed=!0,this.worker&&this.worker.terminate()}},operative.Operative=Operative})();

@@ -5,3 +5,3 @@ {

"description": "Operative: Inline Web-Worker Helper",
"version": "0.0.3",
"version": "0.1.0",
"author": "James Padolsey (http://git.io/padolsey)",

@@ -8,0 +8,0 @@ "main": "dist/operative.min.js",

@@ -124,3 +124,3 @@ # Operative

### Operative API
### Operative API Documentation

@@ -131,4 +131,6 @@ * *{Function}* *operative*: A global function which creates a new Operative module with the passed methods/properties. Note: Non-function properties must be basic objects that can be passed to `JSON.stringify`.

To create an operative module:
#### Creating an Operative:
To create an operative module pass an object of methods/properties:
```js

@@ -145,28 +147,81 @@ var myOperative = operative({

To create an operative module with an internally asynchronous return:
Or a single function to create a singular operative:
```js
var myOperative = operative({
doX: function(a, b, c) {
var iAmDone = this.async();
// Example async stuff ...
setTimeout(function() {
iAmDone(/* The result */);
}, 100);
}
})
var myOperative = operative(function(a, b, c) {
});
// Example call:
myOperative(1, 2, 3, function() { /*callback*/ });
```
On a given operative module you can call your methods directly (from the parent page), e.g.
#### Returning results
The most simple way to use operative is to pass in a callback function when calling an operative function and within the operative method returning the result directly:
```js
myOperative.doX(function(result) {
// This function'll be called when doX() completes within the worker
result; // => Whatever doX() returns
var combine = operative(function(foo, bar) {
return foo + bar;
});
combine('foo', 'bar', function() {
// This callback function will be called with
// the result from your operative function.
result; // => 'foobar'
});
```
And to destroy the operative (and thus its worker):
To implement a basic asynchronous return, but with the same callback pattern, you can utilise `this.async()` within your operative:
```js
var combine = operative(function(foo, bar) {
var finish = this.async();
setTimeout(function() {
finish(foo + bar);
}, 1000); // example async
});
combine('foo', 'bar', function() {
result; // => 'foobar'
});
```
#### Return via Promises
If you don't pass a callback when calling an operative method, operative will assume you want a Promise. Note that operative will reference `operative.Promise` and will expect it to be a [native Promise implementation](http://dom.spec.whatwg.org/#promises) or [compliant polyfill](https://github.com/slightlyoff/Promises). *Operative does not come bundled with a Promise implementation.*
```js
var combine = operative(function(foo, bar) {
// Internally, use a Deferred:
var deferred = this.deferred();
// A deferred has two methods: fulfill & reject:
if (foo !== 'foo') {
// Error (Rejection)
deferred.reject('foo should be "foo"!');
} else {
// Success (Filfillment)
deferred.fulfill(foo + bar);
}
});
// Usage externally:
var promise = combine('foo', 'bar');
promise.then(function(value) {
// Fulfilled
}, function(err) {
// Rejected
});
```
**NOTE:** Operative will only give you a promise if you don't pass a callback *and* if `operative.Promise` is defined. By default `operative.Promise` will reference `window.Promise` (*native implementation if it exists*).
#### Destroying an operative
To destroy the operative (and thus its worker):
```js
o.destroy();

@@ -193,4 +248,11 @@ ```

* 0.0.1 Initial
* 0.0.2 Improved browser support: IE10 support via eval, degraded JSON-marshalling etc.
* 0.0.3 Support for asynchronous returning from within operartive methods (via `this.async()`).
* 0.1.0 (25 Jul 2013) Support Promises (from [Issue #3](https://github.com/padolsey/operative/issues/3)) if they're provided by a [native Promise implementation](http://dom.spec.whatwg.org/#promises) or [compliant polyfill](https://github.com/slightlyoff/Promises)
* 0.0.3 (18 Jul 2013) Support for asynchronous returning from within operartive methods (via `this.async()`).
* 0.0.2 (12 Jul 2013) Improved browser support: IE10 support via eval, degraded JSON-marshalling etc.
* 0.0.1 (11 Jul 2013) Initial
### Contributors
* [James Padolsey](https://github.com/padolsey)
* [Evan Worley](https://github.com/evanworley)
* [Raynos](https://github.com/Raynos)

@@ -9,6 +9,8 @@ /**

* @version 0.0.2
* @contributors
* James Padolsey
*/
(function() {
if (typeof window == 'undefined' && self.importScripts) {
if (typeof window == 'undefined' && self.importScripts) {
// I'm a worker! Run the boiler-script:

@@ -56,4 +58,11 @@ // (Operative itself is called in IE10 as a worker, to avoid SecurityErrors)

operative.Promise = window.Promise;
// Expose:
window.operative = operative;
if (typeof module !== 'undefined' && module.exports) {
module.exports = operative;
} else {
window.operative = operative;
}

@@ -72,2 +81,10 @@ operative.setSelfURL = function(url) {

if (typeof module == 'function') {
// Allow a single function to be passed.
var o = new Operative({ main: module });
return function() {
return o.main.apply(o, arguments);
};
}
module.get = module.get || function(prop) {

@@ -92,2 +109,3 @@ return this[prop];

this.callbacks = {};
this.deferreds = {};

@@ -128,3 +146,3 @@ if (operative.hasWorkerSupport) {

if (typeof property == 'function') {
script.push(' self["' + i.replace(/"/g, '\\"') + '"] = ' + property.toString() + ';');
script.push(' self["' + i.replace(/"/g, '\\"') + '"] = ' + property.toString() + ';');
} else {

@@ -154,3 +172,3 @@ dataProperties[i] = property;

return;
}

@@ -161,13 +179,21 @@

switch (data.cmd) {
case 'console':
case 'console':
window.console && window.console[data.method].apply(window.console, data.args);
break;
case 'result':
if (data.token in this.callbacks) {
var cb = this.callbacks[data.token];
delete this.callbacks[data.token];
cb(data.result);
} else {
throw new Error('Operative: Unmatched token: ' + data.token);
var callback = this.callbacks[data.token];
var deferred = this.deferreds[data.token];
delete this.callbacks[data.token];
delete this.deferreds[data.token];
var deferredAction = data.result && data.result.isDeferred && data.result.action;
if (deferred && deferredAction) {
deferred[deferredAction](data.result.arg);
} else if (callback) {
callback(data.result);
}
break;

@@ -224,3 +250,3 @@ }

});
this._postWorkerMessage({

@@ -244,6 +270,9 @@ definitions: this.dataProperties

var args = slice.call(arguments);
var cb = args.pop();
var cb = typeof args[args.length - 1] == 'function' && args.pop();
if (typeof cb != 'function') {
throw new TypeError('Operative: Expected last argument to be Function (callback)');
if (!cb && !operative.Promise) {
throw new Error(
'Operative: No callback has been passed. Assumed that you want a promise. ' +
'But `operative.Promise` is null. Please provide Promise polyfill/lib.'
);
}

@@ -253,32 +282,59 @@

_self._postWorkerMessage({
method: methodName,
args: args,
token: token
});
if (cb) {
_self.callbacks[token] = cb;
sendToWorker();
} else if (operative.Promise) {
return new operative.Promise(function(deferred) {
_self.deferreds[token] = deferred;
sendToWorker();
});
}
_self.callbacks[token] = cb;
} else {
setTimeout(function() {
if (cb) {
setTimeout(function() {
runInline();
}, 1);
} else if (operative.Promise) {
return new operative.Promise(function(deferred) {
deferred.fulfil = deferred.fulfill;
setTimeout(function() {
runInline(deferred);
}, 1);
});
}
}
var isAsync = false;
function runInline(deferred) {
_self.module.async = function() {
isAsync = true;
return cb;
};
var isAsync = false;
var result = _self.module[methodName].apply(_self.module, args);
_self.module.async = function() {
isAsync = true;
return cb;
};
_self.module.async = function() {
throw new Error('Operative: async() called at odd time');
};
_self.module.deferred = function() {
return deferred;
};
if (!isAsync) {
cb(result);
}
var result = _self.module[methodName].apply(_self.module, args);
}, 1);
_self.module.async = function() {
throw new Error('Operative: async() called at odd time');
};
if (!isAsync && !deferred) {
cb(result);
}
}
function sendToWorker() {
_self._postWorkerMessage({
method: methodName,
args: args,
token: token
});
}
};

@@ -380,18 +436,43 @@

var isAsync = false;
var isDeferred = false;
self.async = function() {
isAsync = true;
return function(r) {
returnResult(r);
};
return function(r) { returnResult(r); };
};
self.deferred = function() {
isDeferred = true;
var def = {};
function fulfill(r) {
returnResult({
isDeferred: true,
action: 'fulfill',
arg: r
});
return def;
}
function reject(r) {
returnResult({
isDeferred: true,
action: 'reject',
arg: r
});
}
def.fulfil = def.fulfill = fulfill;
def.reject = reject;
return def;
};
var result = self[data.method].apply(self, data.args);
// Clear so it's not accidentally used by other code
// Clear async/deferred so they're not accidentally used by other code
self.async = function() {
throw new Error('Operative: async() called at odd time');
};
self.deferred = function() {
throw new Error('Operative: deferred() called at odd time');
};
if (!isAsync) {
if (!isAsync && !isDeferred) {
returnResult(result);

@@ -411,2 +492,1 @@ }

}());

@@ -145,2 +145,55 @@ var async = function async(fn) {

describe('Promise API', function() {
describe('Operative', function() {
var op;
beforeEach(function() {
op = operative(function(beSuccessful) {
var deferred = this.deferred();
if (beSuccessful) {
return deferred.fulfil(873);
} else {
return deferred.reject(999);
}
});
})
it('Should return a promise', function() {
expect(op() instanceof operative.Promise).toBe(true);
});
describe('fulfil()', function() {
it('Should fulfil the exposed promise', function() {
var fulfilled = false;
runs(function() {
op(true).then(function(a) {
expect(a).toBe(873);
fulfilled = true;
}, function() {});
});
waitsFor(function() {
return fulfilled === true;
});
});
});
describe('reject()', function() {
it('Should reject the exposed promise', function() {
var rejected = false;
var fulfilled = false;
runs(function() {
op(false).then(function() {
fulfilled = true;
}, function(err) {
expect(err).toBe(999);
rejected = true;
});
});
waitsFor(function() {
return rejected === true;
});
runs(function() {
expect(fulfilled).toBe(false);
});
});
});
});
});
});

@@ -174,2 +227,5 @@

return this.isWorker;
},
isItAWorker_Promisable: function() {
this.deferred().fulfil(this.isWorker);
}

@@ -186,6 +242,6 @@ });

async(function(nxt) {
o.isItAWorker(function(isWorker) {
o.isItAWorker_Promisable().then(function(isWorker) {
expect(isWorker).toBe(false);
nxt();
});
}, function() {});
});

@@ -192,0 +248,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc