Skip to content

Commit

Permalink
Async.Promise: Refactor state check in _publish() and wait_group in a…
Browse files Browse the repository at this point in the history
…ll()
  • Loading branch information
rhysd committed Dec 27, 2017
1 parent 05e02b4 commit 45cea5d
Showing 1 changed file with 14 additions and 10 deletions.
24 changes: 14 additions & 10 deletions autoload/vital/__vital__/Async/Promise.vim
Original file line number Diff line number Diff line change
Expand Up @@ -64,16 +64,20 @@ endfunction
" ... is added to use this function as a callback of timer_start()
function! s:_publish(promise, ...) abort
let settled = a:promise._state
if settled == s:PENDING
throw 'vital: Async.Promise: Cannot publish a pending promise'
endif

if empty(a:promise._children)
return
endif

for i in range(len(a:promise._children))
if settled == s:FULFILLED
let l:CB = a:promise._fulfillments[i]
elseif settled == s:REJECTED
let l:CB = a:promise._rejections[i]
else
throw 'vital: Async.Promise: Cannot publish a pending promise'
" When rejected
let l:CB = a:promise._rejections[i]
endif
let child = a:promise._children[i]
if type(child) != v:t_none
Expand All @@ -82,6 +86,7 @@ function! s:_publish(promise, ...) abort
call l:CB(a:promise._result)
endif
endfor

let a:promise._children = []
let a:promise._fulfillments = []
let a:promise._rejections = []
Expand Down Expand Up @@ -142,10 +147,10 @@ function! s:_reject(promise, ...) abort
endfunction

function! s:_notify_done(wg, index, value) abort
let a:wg.done[a:index] = a:value
let a:wg.resolved += 1
if a:wg.resolved == a:wg.total
call a:wg.resolve(a:wg.done)
let a:wg.results[a:index] = a:value
let a:wg.remaining -= 1
if a:wg.remaining == 0
call a:wg.resolve(a:wg.results)
endif
endfunction

Expand All @@ -157,10 +162,9 @@ function! s:_all(promises, resolve, reject) abort
endif

let wait_group = {
\ 'done': repeat([v:null], total),
\ 'results': repeat([v:null], total),
\ 'resolve': a:resolve,
\ 'resolved': 0,
\ 'total': total,
\ 'remaining': total,
\ }

" 'for' statement is not available here because iteration variable is captured into lambda
Expand Down

0 comments on commit 45cea5d

Please sign in to comment.