Last active
April 17, 2019 12:04
-
-
Save nareix/fa131298edb988620c5d to your computer and use it in GitHub Desktop.
Promise in lua
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local P = {} | |
P.reject = function (err) | |
return P.new(function (fulfill, reject) | |
reject(err) | |
end) | |
end | |
P.resolve = function (r) | |
return P.new(function (fulfill, reject) | |
fulfill(r) | |
end) | |
end | |
P.new = function (start) | |
local p = {} | |
p._fulfill = function (r) | |
if p._next then p._next._startOk(r) end | |
end | |
p._reject = function (err) | |
if p._next then p._next._startErr(err) end | |
end | |
if start then | |
set_immediate(function () | |
start(p._fulfill, p._reject) | |
end) | |
end | |
local callNext = function (cb, prevRes) | |
if cb == nil then return end | |
local ok, r = pcall(function () | |
return cb(prevRes) | |
end) | |
if not ok then | |
if type(r) ~= 'table' then | |
error(r) | |
end | |
r = Promise.reject(r) | |
elseif not (r and type(r) == 'table' and r._isPromise) then | |
r = Promise.resolve(r) | |
end | |
r.thenDo(function (r) | |
p._fulfill(r) | |
end, function (err) | |
p._reject(err) | |
end) | |
end | |
p._startOk = function (r) | |
callNext(p._cbOk, r) | |
end | |
p._startErr = function (err) | |
callNext(p._cbErr, err) | |
end | |
p._isPromise = true | |
p.catch = function (cbErr) | |
return p.thenDo(nil, cbErr) | |
end | |
p.thenDo = function (cbOk, cbErr) | |
local _next = P.new() | |
p._next = _next | |
_next._cbOk = cbOk | |
_next._cbErr = cbErr | |
return _next | |
end | |
return p | |
end | |
Promise = P | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require('promise') | |
Promise.new(function (fulfill, reject) | |
reject(42) | |
end).thenDo(function (r) | |
info('fulfill', r) | |
end, function (err) | |
info('reject', err) | |
return 43 | |
end).thenDo(function (r) | |
info('step3', r) | |
return 44 | |
end).thenDo(function (r) | |
info('step4', r) | |
end).thenDo(function () | |
return Promise.reject(52).thenDo(function () | |
end, function () | |
return Promise.resolve(53).thenDo(function () | |
return 33 | |
end) | |
end).thenDo(function (r) | |
info('last', r) | |
end) | |
end) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment