Added promise support

This commit is contained in:
Kirill Efimov
2016-01-22 20:32:10 +03:00
committed by Alex Kocharin
parent f333e58640
commit 9cf8df8c22
8 changed files with 417 additions and 6 deletions

View File

@@ -11,7 +11,7 @@ var callable = require('es5-ext/object/valid-callable')
extensions.dispose = function (dispose, conf, options) {
var del;
callable(dispose);
if (options.async && extensions.async) {
if ((options.async && extensions.async) || (options.promise && extensions.promise)) {
conf.on('deleteasync', del = function (id, result) {
apply.call(dispose, null, slice.call(result.args, 1));
});

50
ext/promise.js Normal file
View File

@@ -0,0 +1,50 @@
// Support for functions returning promise
'use strict';
var nextTick = require('next-tick')
, create = Object.create;
require('../lib/registered-extensions').promise = function (tbi, conf) {
var cache = create(null);
// After not from cache call
conf.on('set', function (id, __, promise) {
promise.then(function () {
// nextTick avoids error interception
nextTick(function () {
cache[id] = promise;
conf.emit('setasync', id, 1);
});
}, function () {
nextTick(function () {
conf.delete(id);
});
});
});
// From cache (sync)
conf.on('get', function (id, args, context) {
conf.emit('getasync', id, args, context);
});
// On delete
conf.on('delete', function (id) {
var result;
// If false, we don't have value yet, so we assume that intention is not
// to memoize this call. After value is obtained we don't cache it but
// gracefully pass to callback
if (!cache[id]) return;
result = cache[id];
delete cache[id];
conf.emit('deleteasync', id, result);
});
// On clear
conf.on('clear', function () {
var oldCache = cache;
cache = create(null);
conf.emit('clearasync', oldCache);
});
};