Skip to content

Commit

Permalink
add Promise.json helper
Browse files Browse the repository at this point in the history
  • Loading branch information
BuckarooBanzay committed Jul 31, 2024
1 parent bf75f46 commit 41338ba
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
4 changes: 4 additions & 0 deletions http.lua
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,7 @@ function Promise.http(http, url, opts)
end)
end)
end

function Promise.json(http, url, opts)
return Promise.http(http, url, opts):next(function(res) return res.json() end)
end
7 changes: 7 additions & 0 deletions http.spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ mtt.register("Promise.http GET with async/await", function()
end)
end)

mtt.register("Promise.json GET with async/await", function()
return Promise.async(function(await)
local joke = await(Promise.json(http, "https://api.chucknorris.io/jokes/random"))
assert(type(joke.value) == "string")
end)
end)

mtt.register("Promise.http/all GET", function(callback)
local p1 = Promise.http(http, "https://api.chucknorris.io/jokes/random"):next(toJson)
local p2 = Promise.http(http, "https://api.chucknorris.io/jokes/random"):next(toJson)
Expand Down
12 changes: 12 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,18 @@ end):catch(function(res)
end)
```

## `Promise.json(http, url, opts?)`

Helper function for `Promise.http` that parses a json response

Example:
```lua
-- call chuck norris api: https://api.chucknorris.io/ and expect json-response
Promise.json(http, "https://api.chucknorris.io/jokes/random"):next(function(joke)
assert(type(joke.value) == "string")
end)
```

## `Promise.mods_loaded()`

Resolved on mods loaded (`minetest.register_on_mods_loaded`)
Expand Down

0 comments on commit 41338ba

Please sign in to comment.