Vim documentation: vital/Async/Promise

main help file
vital/Async/Promise.txt       an asynchronous operation like ES6 Promise

Maintainer: rhysd <lin90162@yahoo.co.jp>

==============================================================================
CONTENTS                                Vital.Async.Promise-contents

INTRODUCTION                    Vital.Async.Promise-introduction
REQUIREMENTS                    Vital.Async.Promise-requirements
EXAMPLE                         Vital.Async.Promise-example
CONSTANTS                       Vital.Async.Promise-constants
FUNCTIONS                       Vital.Async.Promise-functions
OBJECTS                         Vital.Async.Promise-objects
  Promise Object                Vital.Async.Promise-objects-Promise
  Exception Object              Vital.Async.Promise-objects-Exception



==============================================================================
INTRODUCTION                            Vital.Async.Promise-introduction

Vital.Async.Promise is a library to represent the eventual completion or
failure of an asynchronous operation. APIs are aligned to ES6 Promise. If you
already know them, you can start to use this library easily.

Instead of callbacks, Promise provides:

- a guarantee that all operations are asynchronous. Functions given to .then()
  method or .catch() method is executed on next tick (or later) using
  timer_start().
- chaining asynchronous operations. Chained operation's order is sequentially
  run and the order is guaranteed.
- persistent error handling using .catch() method. Please be careful of
  floating Promise. All Promise should have .catch() call not to squash an
  exception.
- flow control such as awaiting all Promise objects completed or selecting
  the fastest one of Promises objects.

If you know the detail of APIs, documents for ES6 Promise at Mozilla Developer
Network and ECMA-262 specs would be great.

Mozilla Developer Network:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

ECMA-262:
https://www.ecma-international.org/publications/standards/Ecma-262.htm



==============================================================================
REQUIREMENTS                            Vital.Async.Promise-requirements

Vital.Async.Promise requires lambda and timers features.
So Vim 8.0 or later is required. The recent version of Neovim also supports
them.



==============================================================================
EXAMPLE                                 Vital.Async.Promise-example

Before explaining the detail of APIs, let's see actual examples.

(1) Timer                               Vital.Async.Promise-example-timer

  let s:Promise = vital#vital#import('Async.Promise')

  function! s:wait(ms)
    return s:Promise.new({resolve -> timer_start(a:ms, resolve)})
  endfunction

  call s:wait(500).then({-> execute('echo "After 500ms"', '')})


  One of most simple asynchronous operation is a timer. It calls a specified
  callback when exceeding the timeout. "s:Promise.new" creates a new Promise
  object with given callback. In the callback, function "resolve" (and
  "reject" if needed) is passed. When the asynchronous operation is done (in
  this case, when the timer is expired), call "resolve" on success or call
  "reject" on failure.


(2) Next tick                           Vital.Async.Promise-example-next-tick

  let s:Promise = vital#vital#import('Async.Promise')

  function! s:next_tick()
    return s:Promise.new({resolve -> timer_start(0, resolve)})
  endfunction

  call s:next_tick()
    \.then({-> 'Execute lower priority tasks here'})
    \.catch({err -> execute('echom err', '')})

  By giving 0 to timer_start() as timeout, it waits for "next tick". It's the
  first time when Vim waits for input. It means that Vim gives higher priority
  to user input and executes the script (in the callback of timer_start())
  after.


(3) Job                         Vital.Async.Promise-example-job

  let s:Promise = vital#vital#import('Async.Promise')

  function! s:read(chan, part) abort
    let out = []
    while ch_status(a:chan, {'part' : a:part}) =~# 'open\|buffered'
      call add(out, ch_read(a:chan, {'part' : a:part}))
    endwhile
    return join(out, "\n")
  endfunction

  function! s:sh(...) abort
    let cmd = join(a:000, ' ')
    return s:Promise.new({resolve, reject -> job_start(cmd, {
    \   'drop' : 'never',
    \   'close_cb' : {ch -> 'do nothing'},
    \   'exit_cb' : {ch, code ->
    \     code ? reject(s:read(ch, 'err')) : resolve(s:read(ch, 'out'))
    \   },
    \ })})
  endfunction

  job is a feature to run commands asynchronously. But it is a bit hard to use
  because it requires a callback. By wrapping it with Promise, it makes
  further easier to use commands and handle errors asynchronously.

  s:read() is just a helper function which reads all output of channel from
  the job. So it's not so important.

  Important part is "return ..." in s:sh(). It creates a Promise which starts
  a job and resolves when the given command has done. It calls resolve() when
  the command finished successfully with an output from stdout, and calls
  reject() when the command failed with an output from stderr.

  "ls -l" can be executed as follows:

  call s:sh('ls', '-l')
        \.then({out -> execute('echo "Output: " . out', '')})
        \.catch({err -> execute('echo "Error: " . err', '')})

  As the more complex example, following code clones 4 repositories and shows
  a message when all of them has completed. When one of them fails, it shows
  an error message without waiting for other operations.

  call s:Promise.all([
  \  s:sh('git', 'clone', 'https://github.com/thinca/vim-quickrun.git'),
  \  s:sh('git', 'clone', 'https://github.com/tyru/open-browser-github.git'),
  \  s:sh('git', 'clone', 'https://github.com/easymotion/vim-easymotion.git'),
  \  s:sh('git', 'clone', 'https://github.com/rhysd/clever-f.vim.git'),
  \]
  \)
    \.then({-> execute('echom "All repositories were successfully cloned!"', '')})
    \.catch({err -> execute('echom "Failed to clone: " . err', '')})

  s:Promise.all(...) awaits all given promises have completed, or one of them
  has failed.


(4) Timeout                             Vital.Async.Promise-example-timeout

  Let's see how Promise realizes timeout easily.

  let s:Promise = vital#vital#import('Async.Promise')

  call s:Promise.race([
  \   s:sh('git', 'clone', 'https://github.com/vim/vim.git').then({-> v:false}),
  \   s:wait(10000).then({-> v:true}),
  \]).then({timed_out ->
  \   execute('echom timed_out ? "Timeout!" : "Cloned!"', '')
  \})

  s:sh() and s:wait() are explained above. And .race() awaits one of given
  Promise objects have finished.

  The .race() awaits either s:sh(...) or s:wait(...) has completed or failed.
  It means that it clones Vim repository from GitHub via git command, but if
  it exceeds 10 seconds, it does not wait for the clone operation anymore.

  By adding .then() and giving the result value (v:false or v:true here), you
  can know whether the asynchronous operation was timed out or not in
  succeeding .then() method. The parameter "timed_out" represents it.


(5) REST API call                       Vital.Async.Promise-example-rest-api

  At last, let's see how Promise handles API call with job and curl
  command. Here, we utilize previous "s:sh" function and encodeURIComponent()
  function in Vital.Web.HTTP module to encode a query string.

  let s:HTTP = vital#vital#import('Web.HTTP')

  function! s:github_issues(query) abort
      let q = s:HTTP.encodeURIComponent(a:query)
      let url = 'https://api.github.com/search/issues?q=' . q
      return s:sh('curl', url)
             \.then({data -> json_decode(data)})
             \.then({res -> has_key(res, 'items') ?
               \ res.items :
               \ execute('throw ' . string(res.message))})
  endfunction

  call s:github_issues('repo:vim/vim sort:reactions-+1')
    \.then({issues -> execute('echom issues[0].url', '')})
    \.catch({err -> execute('echom "ERROR: " . err', '')})

  In this example, it searches the issue in Vim repository on GitHub which
  gained the most :+1: reactions.

  In s:github_issues(), it calls GitHub Issue Search API using curl command
  and s:sh() function explained above. And it decodes the returned JSON by
  json_decode() and checks the content. If the curl command failed or API
  returned failure response, the Promise value will be rejected. The rejection
  will be caught in .catch() method at the last line and an error message will
  be shown.



==============================================================================
CONSTANTS                               Vital.Async.Promise-constants

TimeoutError                            Vital.Async.Promise.TimeoutError

        An exception message string returned as {error} in a result list of
        the Vital.Async.Promise.wait() function when timeout has reached.


==============================================================================
FUNCTIONS                               Vital.Async.Promise-functions

new({executor})                         Vital.Async.Promise.new()

        Creates a new Promise object with given {executor}.

        {executor} is a Funcref which represents how to create a Promise
        object. It is called _synchronously_. It receives two functions as
        parameters. The first parameter is "resolve". It accepts one or zero
        argument. By calling it in {executor}, new() returns a resolved
        Promise object. The second parameter is "reject". It also accepts one
        or zero argument. By calling it in {executor}, new() returns rejected
        Promise object.

          " Resolved Promise object with 42
          let p = Promise.new({resolve -> resolve(42)})

          " Rejected Promise object with 'ERROR!'
          let p = Promise.new({_, reject -> reject('ERROR!')})
          let p = Promise.new({-> execute('throw "ERROR!"')})

        When another Promise object is passed to "resolve" or "reject"
        function call, new() returns a pending Promise object which awaits
        until the given other Promise object has finished.

        If an exception is thrown in {executor}, new() returns a rejected
        Promise object with the exception.

        Calling "resolve" or "reject" more than once does not affect.

        If "resolve" or "reject" is called with no argument, it resolves a
        Promise object with v:null.

          " :echo outputs 'v:null'
          Promise.new({resolve -> resolve()})
            \.then({x -> execute('echo x', '')})

resolve([{value}])                      Vital.Async.Promise.resolve()

        Creates a resolved Promise object.
        It is a helper function equivalent to calling "resolve" immediately in
        new():

          " Followings are equivalent
          let p = Promise.resolve(42)
          let p = Promise.new({resolve -> resolve(42)})

        If {value} is a Promise object, it resolves/rejects with a value which
        given Promise object resolves/rejects with.

          call Promise.resolve(Promise.resolve(42))
          \.then({x -> execute('echo x', '')})
          " Outputs '42'

          call Promise.resolve(Promise.reject('ERROR!'))
          \.catch({reason -> execute('echo reason', '')})
          " Outputs 'ERROR!'

reject([{value}])                       Vital.Async.Promise.reject()

        Creates a rejected Promise object.
        It is a helper function equivalent to calling "reject" immediately in
        new():

          " Followings are equivalent
          let p = Promise.reject('Rejected!')
          let p = Promise.new({_, reject -> reject('Rejected!')})

all({promises})                         Vital.Async.Promise.all()

        Creates a Promise object which awaits all of {promises} has completed.
        It resolves the Promise object with a list of results of {promises} as
        following:

          call Promise.all([Promise.resolve(1), Promise.resolve('foo')])
          \.then({arr -> execute('echo arr', '')})
          " It shows [1, 'foo']

        If one of them is rejected, it does not await other Promise objects
        and the Promise object is rejected immediately.


          call Promise.all([Promise.resolve(1), Promise.reject('ERROR!')])
          \.catch({err -> execute('echo err', '')})
          " It shows 'ERROR!'

        If an empty list is given, it is equivalent to Promise.resolve([]).

race({promises})                        Vital.Async.Promise.race()

        Creates a Promise object which resolves or rejects as soon as one of
        {promises} resolves or rejects.

          call Promise.race([
          \  Promise.new({resolve -> timer_start(50, {-> resolve('first')})}),
          \  Promise.new({resolve -> timer_start(100, {-> resolve('second')})}),
          \])
          \.then({v -> execute('echo v', '')})
          " It outputs 'first'

          call Promise.race([
          \  Promise.new({resolve -> timer_start(50, {-> execute('throw "ERROR!"')})}),
          \  Promise.new({resolve -> timer_start(100, {-> resolve('second')})}),
          \])
          \.then({v -> execute('echo v', '')})
          \.catch({e -> execute('echo e', '')})
          " It outputs 'ERROR!'

        If {promises} is an empty list, the returned Promise object will never
        be resolved or rejected.

wait({promise}[, {options}])            Vital.Async.Promise.wait()

        Waits synchronously until a given {promise} has become resolved and
        returns a [{result}, {error}] list.

        The {result} is a {value} passed to Vital.Async.Promise.resolve()
        when a given {promise} has resolved. Otherwise it is v:null.

        The {error} is a {value} passed to Vital.Async.Promise.reject()
        when a given {promise} has rejected or Async.Promise.TimeoutError
        when a given {timeout} has passed. Otherwise it is v:null.

        The following {options} are available

        "timeout"       Timeout in milliseconds. When timeout, the function
                        returns a [v:null, Async.Promise.TimeoutError]
                        list.
                        When it is v:null, the function waits a given
                        {promise} for ever.
                        Default: v:null
        "interval"      Interval delay of an internal loop in milliseconds.
                        Default: 30

        let [result, error] = Promise.wait(p, { 'timeout': 1000 })

        if error ==# Promise.TimeoutError
          echo 'Timeout!'
        elseif error isnot# v:null
          echoerr "Failed:" . string(error)
        else
          echo "Success:" . string(result)
        endif

        For convenience, users can directly specify the "timeout" in the
        second argument like

        call Promise.wait(p, 1000)
        " Is equivalent to call Promise.wait(p, {'timeout': 1000})

chain({promise_factories})              Vital.Async.Promise.chain()
        Chain promises produced by {promise_factories} (List of Function)
        and return a promise which resolves to a result List which contains
        result of each produced promises.
        It is like an asynchronous sequential call. It rejects when one of
        function in {promise_factories} has failed or produced promises
        rejects. Note that it stops producing promises by functions after
        rejection.

        let fs = [
              \ { -> Promise.new({ r -> timer_start(50, { -> r('1') })})},
              \ { -> Promise.new({ r -> timer_start(50, { -> r('2') })})},
              \ { -> Promise.new({ r -> timer_start(50, { -> r('3') })})},
              \]
        call Promise.chain(fs)
        " --------1--------2--------3----> RESOLVE
        "         50ms     100ms    150ms

        let fs = [
              \ { -> Promise.new({ r -> timer_start(50, { -> r('1') })})},
              \ { -> execute('throw "Error"') },
              \ { -> Promise.new({ r -> timer_start(50, { -> r('3') })})},
              \]
        call Promise.chain(fs)
        " --------1----> REJECT
        "         50ms

        let fs = [
              \ { -> Promise.new({ r -> timer_start(50, { -> r('1') })})},
              \ { -> Promise.new({ _, rj -> timer_start(50, { -> rj('2') })})},
              \ { -> Promise.new({ r -> timer_start(50, { -> r('3') })})},
              \]
        call Promise.chain(fs)
        " --------1--------2----> REJECT
        "         50ms     100ms

on_unhandled_rejection({callback})      Vital.Async.Promise.on_unhandled_rejection

        Set callback to catch all unhandled rejected promise's result.
        If {callback} throws error, Async.Promise does not handle it.

        The {callback} is Funcref, it's argument can be unhandled thrown error or unhandled rejected value.

        Note:
        This callback will called even if you using Vital.Async.Promise.wait().
        If you want to clear callback, you can use following codes.


        call Promise.on_unhandled_rejection(Promise.noop)


is_promise({value})                     Vital.Async.Promise.is_promise()

        Returns TRUE when {value} is a Promise object. Otherwise, returns
        FALSE.

is_available()                          Vital.Async.Promise.is_available()

        Returns TRUE when requirements for using Vital.Async.Promise are
        met. Please look at Vital.Async.Promise-requirements to know the
        detail of the requirements.
        Otherwise, returns FALSE.

          if Promise.is_available()
            " Asynchronous operations using Promise
          else
            " Fallback into synchronous operations
          endif



==============================================================================
OBJECTS                                 Vital.Async.Promise-objects

------------------------------------------------------------------------------
Promise Object                          Vital.Async.Promise-objects-Promise

Promise object represents the eventual completion or failure of an
asynchronous operation. It represents one of following states:

- Operation has not done yet
- Operation has completed successfully
- Operation has failed with an error

                                        Vital.Async.Promise-Promise.then()
{promise}.then([{onResolved} [, {onRejected}]])

        Creates a new Promise object which is resolved/rejected after
        {promise} is resolved or rejected. {onResolved} and {onRejected} must
        be Funcref and they are guaranteed to be called __asynchronously__.

          echo 'hi'
          call Promise.new({resolve -> execute('echo "halo" | call resolve(42)', '')})
          \.then({-> execute('echo "bye"', '')}, {-> execute('echo "ah"', '')})
          echo 'yo'

        Above script outputs messages as following:

          hi
          halo
          yo
          bye

        If {onResolved} is specified, it is called after {promise} is
        resolved. When {onResolved} returns non-Promise value, the returned
        Promise object from .then() is resolved with it.
        When {onResolved} returns a Promise object, the returned Promise
        object awaits until the Promise object has finished.

        If {onRejected} is specified, it is called after {promise} is
        rejected. When {onRejected} returns non-Promise value, the returned
        Promise object from .then() is resolved with it.
        When {onRejected} returns a Promise object, the returned Promise
        object awaits until the Promise object has finished.

        When an exception is thrown in {onResolved} or {onRejected}, the
        returned Promise object from .then() will be rejected with an
        exception object.
        Please read Vital.Async.Promise-objects-Exception to know an
        exception object.

          " Both followings create a rejected Promise value asynchronously
          call Promise.resolve(42).then({-> execute('throw "ERROR!"')})
          call Promise.resolve(42).then({-> Promise.reject('ERROR!')})

        {onResolved} and {onRejected} can be v:null.

{promise}.catch([{onRejected}])         Vital.Async.Promise-Promise.catch()

        It is a shortcut function of calling .then() where the first argument
        is v:null.

          " Followings are equal
          call Promise.reject('ERROR').then(v:null, {msg -> execute('echo msg', '')})
          call Promise.reject('ERROR').catch({msg -> execute('echo msg', '')})

{promise}.finally([{onFinally}])        Vital.Async.Promise-Promise.finally()

        It returns a Promise and the passed callback is called once the
        promise is settled, whether fulfilled or rejected.
        This provides a way for code that must be executed once the promise
        has been dealt with to be run whether it was fulfilled successfully or
        rejected. {onFinally} is a Funcref which has no parameter.

          " Both followings echo 'on finally'
          call Promise.resolve(42).finally({-> execute('echo "on finally"', '')})
          call Promise.reject('ERROR!').finally({-> execute('echo "on finally"', '')})

        :throw in the {onFinally} callback will reject the new promise with
        the thrown error.

        Unlike passing the callback to both 1st and 2nd parameters of
        .then(), it propagates its receiver's result.

          " Following echoes 42
          call Promise.resolve(42)
            \.finally({-> v:null})
            \.then({x -> execute('echo x', '')})

        Note:
        As an above code, .finally() is different from .then() in terms of
        the resolved/rejected value. Promise.resolve(42).finally() resolves
        with 42, but Promise.resolve(42).then({-> v:null}, {-> v:null})
        resolves with v:null.



------------------------------------------------------------------------------
Exception Object                        Vital.Async.Promise-objects-Exception

Exception object represents an exception of Vim script. Since Vim script's
v:exception is a String value and a stack trace of the exception is
separated to v:throwpoint variable, it does not fit Promise API.
So we need to define our own exception object. It is passed to {onRejected}
parameter of .then() or .catch() method.

Example:

  call Promise.new({-> execute('throw "ERROR!"')})
    \.catch({ex -> execute('echo ex', '')})
  " Output:
  " {'exception': 'ERROR!', 'throwpoint': '...'}

  call Promise.new({-> 42 == []})
    \.catch({ex -> execute('echo ex', '')})
  " Output:
  " {'exception': 'Vim(return):E691: ...', 'throwpoint': '...'}

Exception object has two fields; "exception" and "throwpoint".
"exception" is an error message. It's corresponding to v:exception. And
"throwpoint" is a stack trace of the caught exception. It's corresponding to
v:throwpoint.

==============================================================================
vim:tw=78:fo=tcq2mM:ts=8:ft=help:norl

top - main help file - tag index