Async and Await Around m.request

by viniciusCamargo

Level: beginner • Mithril.js Version: latest

This example demonstrates the use of JavaScripts async and await keywords. In this case the keywords are used for the oninit lifecycle method and act as simple wrapper around Mithril.js' m.request. The api request itself is surrounded by a try...catch block. Let's see the example.

Live Example


Type Name URL


const api = {
  path: '',
  getPosts() {
    return m.request({ url: `${api.path}/posts` })

const postView = ({ title, body }) => m('div', [
  m('h2', title),
  m('p', body)

const Posts = {
  posts: [],
  error: '',

  async oninit({state}) {
    try {
      state.posts = await api.getPosts()
    } catch (error) {
      state.error = error.message

  view({state}) {
    return state.error
      ? m('p', state.error)

m.mount(document.body, Posts)

As a prerequisite for this snippet, the latest version of Mithril.js framework is required. Beginners should have no problems following this example, that simply shows some basic recipies.

Here we can see use cases of different Mithril.js API methods like m.request or m.mount, besides the centrepiece m() hyperscript function. Moreover, it shows how the lifecycle method oninit can be used (better known as hook).

The example was written by viniciusCamargo, last edits were made on 26 October 2021.


Did you note a typo or something else? So let me know by opening an issue. Or much better: just fork the repository on GitHub, push your commits and send a pull request. Ready to start your work? Then click on the edit link below. Thanks in advance!

See more code examples  •  Edit this example on GitHub