Permalink
Browse files

util, feat: support custom Promise object in util.syn.

  • Loading branch information...
xicilion committed Dec 8, 2017
1 parent 0c97518 commit 29f5cb6fe4465813f6d503c7714493defdc3408d
Showing with 57 additions and 8 deletions.
  1. +21 −8 fibjs/src/util/util_sync.cpp
  2. +36 −0 test/util_test.js
@@ -108,18 +108,31 @@ static void async_promise(const v8::FunctionCallbackInfo<v8::Value>& args)
if (result.IsEmpty())
return;
if (!result->IsPromise()) {
v8::Local<v8::Function> _then;
v8::Local<v8::Function> _catch;
v8::Local<v8::Value> v;
if (result->IsObject()) {
v8::Local<v8::Object> o = v8::Local<v8::Object>::Cast(result);
v = o->Get(isolate->NewString("then"));
if (v->IsFunction())
_then = v8::Local<v8::Function>::Cast(v);
v = o->Get(isolate->NewString("catch"));
if (v->IsFunction())
_catch = v8::Local<v8::Function>::Cast(v);
}
if (_then.IsEmpty() || _catch.IsEmpty()) {
ThrowError("not async function.");
return;
}
v8::Local<v8::Promise> p = v8::Local<v8::Promise>::Cast(result);
v8::Local<v8::Context> _context = p->CreationContext();
p->Then(_context, isolate->NewFunction("promise_then", promise_then, args[len - 1]))
.ToLocalChecked();
p->Catch(_context, isolate->NewFunction("promise_catch", promise_catch, args[len - 1]))
.ToLocalChecked();
v = isolate->NewFunction("promise_then", promise_then, args[len - 1]);
_then->Call(result, 1, &v);
v = isolate->NewFunction("promise_catch", promise_catch, args[len - 1]);
_catch->Call(result, 1, &v);
}
result_t util_base::sync(v8::Local<v8::Function> func, bool async_func, v8::Local<v8::Function>& retVal)
View
@@ -1180,6 +1180,42 @@ describe('util', () => {
assert.equal(t1, 300);
});
it('custom promise', () => {
class SimplePromise {
constructor(fn) {
this.callbacks = [];
this.failbacks = [];
setImmediate(() => {
fn(this.resolve.bind(this), this.reject.bind(this));
});
}
resolve(res) {
if (this.callbacks.length > 0) this.callbacks.shift()(res, this.resolve.bind(this), this.reject.bind(this));
}
reject(res) {
this.callbacks = [];
if (this.failbacks.length > 0) this.failbacks.shift()(res, this.resolve.bind(this), this.reject.bind(this));
}
catch (fn) {
this.failbacks.push(fn);
}
then(fn) {
this.callbacks.push(fn);
return this;
}
};
function async_test(a, b) {
return new SimplePromise(function (resolve, reject) {
resolve(a + b);
});
}
var t1 = util.sync(async_test, true)(100, 200);
assert.equal(t1, 300);
});
it("err func", () => {
function async_test(a, b) {
return 100;

0 comments on commit 29f5cb6

Please sign in to comment.