diff --git a/CHANGELOG.md b/CHANGELOG.md index 30d1390..e05b371 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ - Promise.Status members are now strings instead of symbols, and indexing a non-existent value will error. - Improve stack traces - Promise.promisify will now turn errors into rejections even if they occur after a yield. +- Add Promise.try # 2.4.0 diff --git a/lib/README.md b/lib/README.md index a47b288..e0b3031 100644 --- a/lib/README.md +++ b/lib/README.md @@ -144,7 +144,7 @@ docs: ``` static: true params: - - name: function + - name: callback type: kind: function params: "...: ...any?" @@ -170,6 +170,37 @@ docs: static: true params: "value: ...any" returns: Promise<...any> + - name: try + desc: | + Begins a Promise chain, calling a synchronous function and returning a Promise resolving with its return value. If the function errors, the returned Promise will be rejected with the error. + + `Promise.try` is similar to [[Promise.promisify]], except the callback is executed instantly, and unlike `promisify`, yielding is not allowed with `try`. + + ```lua + Promise.try(function() + return math.random(1, 2) == 1 and "ok" or error("Oh an error!") + end) + :andThen(function(text) + print(text) + end) + :catch(function(err) + warn("Something went wrong") + end) + ``` + static: true + params: + - name: callback + type: + kind: function + params: "...: ...any?" + returns: "...any?" + - name: "..." + type: "...any?" + desc: Arguments for the callback + returns: + - type: "Promise<...any?>" + desc: The return value of the passed callback. + - name: all desc: | Accepts an array of Promises and returns a new promise that: diff --git a/lib/init.lua b/lib/init.lua index f957487..a658704 100644 --- a/lib/init.lua +++ b/lib/init.lua @@ -247,6 +247,13 @@ function Promise.reject(...) end) end +--[[ + Begins a Promise chain, turning synchronous errors into rejections. +]] +function Promise.try(...) + return Promise.resolve():andThenCall(...) +end + --[[ Returns a new promise that: * is resolved when all input promises resolve diff --git a/lib/init.spec.lua b/lib/init.spec.lua index 9f64bd2..fdd613f 100644 --- a/lib/init.spec.lua +++ b/lib/init.spec.lua @@ -685,4 +685,17 @@ return function() expect(finalValue).to.equal(1) end) end) + + describe("Promise.try", function() + it("should catch synchronous errors", function() + local errorText + Promise.try(function() + error('errortext') + end):catch(function(e) + errorText = e + end) + + expect(errorText:find("errortext")).to.be.ok() + end) + end) end \ No newline at end of file