### Install lua-promises using LuaRocks Source: https://github.com/zserge/lua-promises/blob/master/README.md Provides the command to install the lua-promises library using LuaRocks, the package manager for Lua. ```bash luarocks install --server=http://luarocks.org/dev lua-promises ``` -------------------------------- ### Getting the First Settled Promise with deferred.first() Source: https://github.com/zserge/lua-promises/blob/master/docs/index.html Illustrates `deferred.first()` which returns a promise that resolves or rejects as soon as the first promise in the input list settles. Includes an example with a timeout promise. ```lua function timeout(sec) local d = deferred.new() settimeout(function() d:reject('Timeout') end, sec) return d end deferred.first({ read(somefile), timeout(5), }):next(function(result) end, function(err) end) ``` -------------------------------- ### Promise Chaining with :next() Source: https://github.com/zserge/lua-promises/blob/master/docs/index.html Illustrates how to chain asynchronous operations using the `Promise:next()` method. This example shows reading two files sequentially, handling results and errors at each step. ```lua read('first.txt'):next(function(s) print('File file:', s) return read('second.txt') end):next(function(s) print('Second file:', s) end):next(nil, function(err) print('Error', err) end) ``` -------------------------------- ### Nested callback example Source: https://github.com/zserge/lua-promises/blob/master/README.md Illustrates a scenario with multiple sequential asynchronous operations (connect, auth, request) using nested callbacks, highlighting the complexity and potential for unmanageable code. ```lua connect(function(status, err) if err then .... end auth(function(token, err) if err then ... end request(token, function(res, err) if err then ... end handleresult(res) end) end) end) ``` -------------------------------- ### Wait for All Promises (Lua) Source: https://github.com/zserge/lua-promises/blob/master/README.md Starts multiple asynchronous actions in parallel and waits for all of them to complete. The `next` method handles the results or errors from all promises. ```lua deferred.all({ http.get('http://example.com/first'), http.get('http://example.com/second'), http.get('http://example.com/third'), }):next(function(results) -- handle results here (all requests are finished and there has been -- no errors) end, function(results) -- handle errors here (all requests are finished and there has been -- at least one error) end) ``` -------------------------------- ### Deferred Promise Creation and Usage Source: https://github.com/zserge/lua-promises/blob/master/docs/index.html Demonstrates how to create a new promise using `deferred.new()` and how to resolve or reject it based on an asynchronous operation's outcome. It shows how to wrap a callback-based API into a promise-based one. ```lua local deferred = require('deferred') function read(f) local d = deferred.new() readasync(f, function(contents, err) if err == nil then d:resolve(contents) else d:reject(err) end end) return d end read('file.txt'):next(function(s) print('File.txt contents: ', s) end, function(err) print('Error', err) end) ``` -------------------------------- ### Promise Class API Reference Source: https://github.com/zserge/lua-promises/blob/master/docs/index.html API documentation for the Promise class, detailing methods for handling asynchronous operations. Includes 'next' for callbacks, 'resolve' to fulfill the promise, and 'reject' to fail it. ```APIDOC Class Promise A promise is an object that can store a value to be retrieved by a future object. Promise:next (cb[, errcb]) Wait for the promise object. Parameters: * cb function resolve callback (function(value) end) * errcb function rejection callback (function(reject_value) end) (_optional_) Usage: read('first.txt'):next(function(s) print('File file:', s) return read('second.txt') end):next(function(s) print('Second file:', s) end):next(nil, function(err) print('Error', err) end) Promise:resolve (value) Resolve promise object with value. Parameters: * value promise value Returns: resolved future result Promise:reject (value) Reject promise object with value. Parameters: * value promise value Returns: rejected future result ``` -------------------------------- ### Deferred Module Functions API Reference Source: https://github.com/zserge/lua-promises/blob/master/docs/index.html API documentation for the deferred module functions. Covers 'new' for creating promises, 'all' for concurrent execution, 'map' for sequential processing, and 'first' for the earliest settled promise. ```APIDOC Module deferred A+ promises in Lua. new (options) Returns a new promise object. Parameters: * options Returns: [Promise](index.html#Promise) New promise Usage: local deferred = require('deferred') function read(f) local d = deferred.new() readasync(f, function(contents, err) if err == nil then d:resolve(contents) else d:reject(err) end end) return d end read('file.txt'):next(function(s) print('File.txt contents: ', s) end, function(err) print('Error', err) end) all (args) Returns a new promise object that is resolved when all promises are resolved/rejected. Parameters: * args list of promise Returns: [Promise](index.html#Promise) New promise Usage: deferred.all({ http.get('http://example.com/first'), http.get('http://example.com/second'), http.get('http://example.com/third'), }):next(function(results) end, function(results) end) map (args, fn) Returns a new promise object that is resolved with the values of sequential application of function fn to each element in the list. fn is expected to return promise object. Parameters: * args list of promise * fn promise used to resolve the list of promise Returns: a new promise Usage: local items = {'a.txt', 'b.txt', 'c.txt'} deferred.map(items, read):next(function(files) end, function(err) end) first (args) Returns a new promise object that is resolved as soon as the first of the promises gets resolved/rejected. Parameters: * args list of promise Returns: [Promise](index.html#Promise) New promise Usage: function timeout(sec) local d = deferred.new() settimeout(function() d:reject('Timeout') end, sec) return d end deferred.first({ read(somefile), timeout(5), }):next(function(result) end, function(err) end) ``` -------------------------------- ### Handling Multiple Promises with deferred.all() Source: https://github.com/zserge/lua-promises/blob/master/docs/index.html Shows how to use `deferred.all()` to manage multiple promises concurrently. The returned promise resolves when all input promises are settled, providing results or errors. ```lua deferred.all({ http.get('http://example.com/first'), http.get('http://example.com/second'), http.get('http://example.com/third'), }):next(function(results) end, function(results) end) ``` -------------------------------- ### Chaining promises for sequential file reading Source: https://github.com/zserge/lua-promises/blob/master/README.md Illustrates how to chain multiple asynchronous file read operations sequentially using promises. Each `next` call can return another promise, allowing for a clear and linear flow of asynchronous tasks. ```lua -- Reading two files sequentially: read('first.txt'):next(function(s) print('File file:', s) return read('second.txt') end):next(function(s) print('Second file:', s) end):next(nil, function(err) -- error while reading first or second file print('Error', err) end) ``` -------------------------------- ### Create a new promise object Source: https://github.com/zserge/lua-promises/blob/master/README.md Shows the basic API call to create a new, unresolved promise object using the 'deferred' module. ```APIDOC deferred.new() Returns a new promise object `d`. ``` -------------------------------- ### Create a promise that resolves with the first settled promise Source: https://github.com/zserge/lua-promises/blob/master/README.md Describes the creation of a promise that resolves or rejects as soon as any of the provided promises in the input list settles. ```APIDOC deferred.first(promises) Returns a new promise object `d` that is resolved as soon as the first of the `promises` gets resolved/rejected. ``` -------------------------------- ### Require deferred module in Lua Source: https://github.com/zserge/lua-promises/blob/master/README.md Demonstrates how to load the 'deferred' module, which provides the promise functionality, within a Lua script. ```lua local deferred = require('deferred') ``` -------------------------------- ### Create a promise by mapping a function over a list Source: https://github.com/zserge/lua-promises/blob/master/README.md Details the creation of a promise that resolves with the results of applying a function (expected to return a promise) to each element of a list sequentially. ```APIDOC deferred.map(list, fn) Returns a new promise object `d` that is resolved with the values of sequential application of function `fn` to each element in the `list`. `fn` is expected to return promise object. ``` -------------------------------- ### Sequential Promise Execution with deferred.map() Source: https://github.com/zserge/lua-promises/blob/master/docs/index.html Demonstrates `deferred.map()` for executing a function sequentially on a list of items, where the function itself returns a promise. This is useful for processing lists of asynchronous tasks. ```lua local items = {'a.txt', 'b.txt', 'c.txt'} deferred.map(items, read):next(function(files) end, function(err) end) ``` -------------------------------- ### Reject a promise with a reason Source: https://github.com/zserge/lua-promises/blob/master/README.md API method to transition a promise object from an unresolved state to a rejected state, typically with an error reason. ```APIDOC d:reject(value) Reject promise object with `value`. ``` -------------------------------- ### Convert callback-based API to promise-based Source: https://github.com/zserge/lua-promises/blob/master/README.md Demonstrates the pattern for converting a traditional callback-based asynchronous function into a promise-returning function. This involves creating a deferred object, initiating the async operation, and resolving or rejecting the deferred object based on the operation's outcome. ```lua local deferred = require('deferred') function read(f) local d = deferred.new() readasync(f, function(contents, err) if err == nil then d:resolve(contents) else d:reject(err) end end) return d end -- Example usage: read('file.txt'):next(function(s) print('File.txt contents: ', s) end, function(err) print('Error', err) end) ``` -------------------------------- ### Callback-based asynchronous file read Source: https://github.com/zserge/lua-promises/blob/master/README.md Demonstrates a typical asynchronous file reading operation using callbacks in Lua. This pattern can lead to deeply nested code when multiple asynchronous actions depend on each other. ```lua readfile('file.txt', function(contents, err) if err then print('Error', err) else -- process file contents end end) ``` -------------------------------- ### Promise-based asynchronous operations Source: https://github.com/zserge/lua-promises/blob/master/README.md Shows how the same asynchronous operations (connect, auth, request) can be rewritten using promises, resulting in cleaner, more readable, and error-manageable code. ```lua connect():next(function(status) return auth() end):next(function(token) return request(token) end):next(function(result) handleresult(res) end, function(err) ...handle error... end) ``` -------------------------------- ### Resolve a promise with a value Source: https://github.com/zserge/lua-promises/blob/master/README.md API method to transition a promise object from an unresolved state to a resolved state with a specific value. ```APIDOC d:resolve(value) Resolve promise object with `value`. ``` -------------------------------- ### Create a promise that resolves when all promises resolve Source: https://github.com/zserge/lua-promises/blob/master/README.md Explains how to create a promise that aggregates multiple promises, resolving only when all input promises have settled (resolved or rejected). ```APIDOC deferred.all(promises) Returns a new promise object `d` that is resolved when all `promises` are resolved/rejected. ``` -------------------------------- ### Asynchronously processing a list of files Source: https://github.com/zserge/lua-promises/blob/master/README.md Shows how to use `deferred.map` to process a list of items (file names in this case) asynchronously. The `read` function, which returns a promise, is applied to each item, and the results are collected once all operations are complete. ```lua local items = {'a.txt', 'b.txt', 'c.txt'} -- Read 3 files, one by one deferred.map(items, read):next(function(files) -- here files is an array of file contents for each of the files end, function(err) -- handle reading error end) ``` -------------------------------- ### Wait for First Promise with Timeout (Lua) Source: https://github.com/zserge/lua-promises/blob/master/README.md Waits for the first promise in a group to resolve or reject. Includes a helper function `timeout` to create a promise that rejects after a specified duration, useful for implementing timeouts. ```lua -- returns a promise that gets rejected after a certain timeout function timeout(sec) local d = deferred.new() settimeout(function() d:reject('Timeout') end, sec) return d end deferred.first({ read(somefile), -- resolves promise with contents, or rejects with error timeout(5), }):next(function(result) ...file was read successfully... end, function(err) ...either timeout or I/O error... end) ``` -------------------------------- ### Chain callbacks to a promise Source: https://github.com/zserge/lua-promises/blob/master/README.md Enqueues callbacks to be executed when the promise is resolved or rejected. The resolve callback can be omitted. ```APIDOC d:next(cb, [errcb]) Enqueues resolve callback `cb` and (optionally) a rejection callback `errcb`. Resolve callback can be nil. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.