React/redux application uses async/await

Source: Internet
Author: User
async/await


Async/await is a new feature of the ES7 standard that has not yet been officially announced. In short, you'll want to write asynchronous code in a synchronized way. For the front-end, the writing of asynchronous task code has gone through the callback to the current Promise and will eventually evolve into async/await. Although this feature has not yet been officially released, the use of Babel Polyfill we can already use it in the application.



Http://www.tuicool.com/articles/B77zAbe



Now assuming a simple react/redux application, I'll introduce async/await to its code. Actions



In this example, there is an Action to create a new article, the traditional method is to use Promise combined with redux-thunk middleware implementation.


Import Axios from ' Axios '

export default function createpost (params) {  
    Const success = (Result) => {
        Dispa TCH ({
            type: ' create_post_success ',
            payload:result
        }) return result
    }

    Const FAIL = (ERR) = > {
        dispatch ({
            type: ' Create_post_fail ',
            err
        }) return
        err
    } return

    dispatch = > {return
        axios.post (' http://xxxxx ', params)
        . Then (success)
        . catch (fail)
    }
}


Now rewrite it as a async/await implementation:


Import Axios from ' Axios '

export default function createpost (params) {  
    Const success = (Result) => {
        Dispa TCH ({
            type: ' create_post_success ',
            payload:result
        }) return result
    }

    Const FAIL = (ERR) = > {
        dispatch ({
            type: ' Create_post_fail ',
            err
        }) return
        err
    } return

    Async Dispatch => {
        try {
            const result = await axios.post (' http://xxxxx ', params) return
            success (result) c19/>} catch (Err) {return
            fail (ERR)}}}


Async and await are used in pairs, and are characterized by making the code look like the synchronized code. Components



Also, in the react component, compare the similarities and differences between the Promise and Async/await methods.



Traditionally used Promise:


import React, { Component } from 'react'  
import { connect } from 'react-redux'  
import { createPost } from '../actions/post'

class PostEditForm extends Component {  
    constructor(props) {
        super(props)
    }

    contributePost = e => {
        e.preventDefault()

        // .... get form values as params

        this.props.createPost(params)
        .then(response => {
            // show success message
        })
        .catch(err => {
            // show error tips
        })
    }

    render () {
        return (
            <form onSubmit={this.contributePost}>
                <input name="title"/>
                <textarea name="content"/>
                <button>Create</button>
            </form>
        )
    }
}

export default connect(null, dispatch => {  
    return {
        createPost: params => dispatch(createPost(params))
    }
})(PostEditForm)


If you use async/await


import React, { Component } from 'react'  
import { connect } from 'react-redux'  
import { createPost } from '../actions/post'

class PostEditForm extends Component {  
    constructor(props) {
        super(props)
    }

    async contributePost = e => {
        e.preventDefault()

        // .... get form values as params

        try {
            const result = await this.props.createPost(params)
            // show success message
        } catch (err) {
            // show error tips
        }
    }

    render () {
        return (
            <form onSubmit={this.contributePost}>
                <input name="title"/>
                <textarea name="content"/>
                <button>Create</button>
            </form>
        )
    }
}

export default connect(null, dispatch => {  
    return {
        createPost: params => dispatch(createPost(params))
    }
})(PostEditForm)

The

can be seen, the two patterns, async\await  more intuitive and concise, is the future trend. But at present, it is also necessary to use the Babel  transform-async-to-module-method  plug-in to convert its browser-supported syntax, although there is no performance improvement, but for code authoring experience is better.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.