The mutual transformation between Promise's then and async await

Originally, they were used to process promise. Today, when using react native tree, I found that the author highly praised the writing method of async await
So I studied it and replaced my code
Let's get to the point

When I save values, I write as follows:

    // Stored value
    createData(title, successBack, errorBack) {
        // Use key to save data
        storage.save({
            key: title,   
            data: 'true',
        }).then(successBack(), errorBack());
    }

Then I use async + await to write:

    //Stored value
    async createData1(title, successBack, errorBack) {
        try {
            // Use key to save data
            await storage.save({
                key: title,  
                data: 'true',
            });
            successBack()
        } catch (e) {
            errorBack()
        }
    }

In fact, the latter method seems to be easier to understand. async represents asynchronous operation, which means that this method is asynchronous. Wait,
The code block can be understood as executing the following successBack() method when the execution is completed, and executing errorBack() when there is an error
try catch!

Of course, this way of writing is that the waiting things don't use to return results, so how to pass the value out if there are returned results?
So I rewrite the value taking method:

Let's look at how the document is written:

// query
    inquireData() {
        storage.load({
            key:'storageTest',
            autoSync: true,
            syncInBackground: true,
            syncParams: {
                extraFetchOptions: {
                    // Various parameters
                },
                someFlag: true,
            },
        }).then(ret => {

            this.setState({
                data: ret.name
            });

        }).catch(err => {

            console.warn(err.message);
            switch (err.name) {
                case 'NotFoundError':
                    // To update
                    this.setState({
                        data:'Data is empty.'
                    });

                    break;
                case 'ExpiredError':
                    // TODO
                    break;
            }
        })
    }

Then I changed it:

async select(title, successBack, errorBack) {
        // read
        try {
            const l = await storage.load({
                key: title,
                autoSync: true,
                syncInBackground: true,
                syncParams: {
                    extraFetchOptions: {
                        // Various parameters
                    },
                    someFlag: true,
                },
            })
            successBack(l)
        } catch (e) {
            errorBack(e);
        }
    }

It may be an illusion, but it always looks better
Last complete:

/**
 * Created by Zhuo Yuan on 2018/3/20.
 * zhuoyuan93@gmail.com
 */
import React from 'react';
import {
    View,
    StyleSheet,
} from 'react-native';
import {Checkbox} from 'teaset';
import * as ScreenUtil from "../util/ScreenUtil";

export default class CheckBox extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            checked: false,
        }
    }

    componentDidMount() {
        let {title} = this.props.item;
        this.select(title, (result) => {
                console.log(title + ':' + result)
                if (result) {
                    this.setState({
                        checked: true
                    })
                }
            },
            (err) => console.warn(err.message))


    }

    render() {
        let {title} = this.props.item;
        return (
            <View style={styles.checkView}>
                <Checkbox
                    title={title}
                    checked={this.state.checked}
                    onChange={checked => this._changeChecked(checked)}
                    size={'lg'}
                />
            </View>
        )

    }


    _changeChecked(checked) {

        let {title} = this.props.item;
        if (checked) {
            //storage
            this.createData(title, () => console.log('Storage success'),
                error => console.log(error),);

        } else {
            this.delete(title, () => console.log('Delete success'));
        }
    }

    // increase
    async createData(title, successBack, errorBack) {
        try {
            // UsekeySave data
            await storage.save({
                key: title,    // Be careful:Please do not key Use in_Underline symbol!
                data: 'true',

                // Set asnull,It is not expired.,The time effect of initialization will be overwritten here
                // expires: 1000 * 60
            });
            successBack()
        } catch (e) {
            errorBack()
        }
        //.then(() => alert('Success'), () => alert('fail'));
    }

    async select(title, successBack, errorBack) {
        // read
        try {
            const l = await storage.load({
                key: title,
                // autoSync(Default istrue)This means that the corresponding sync Method
                autoSync: true,

                // syncInBackground(Default istrue)Means that if the data expires,
                // In call sync Method first returns the expired data.
                // Set tofalseIf so, wait sync Method provides the latest data(Of course, it will take more time). 
                syncInBackground: true,

                // You can also give sync Method to pass additional parameters
                syncParams: {
                    extraFetchOptions: {
                        // Various parameters
                    },
                    someFlag: true,
                },
            })
            successBack(l)
        } catch (e) {
            errorBack(e);
        }
    }

    async delete(title, successBack) {
        try {
            await storage.remove({
                key: title
            });
            successBack()
        } catch (e) {
            console.error(e.message)
        }

    }


}

const styles = StyleSheet.create({
    checkView: {
        width: ScreenUtil.screenW / 2,
        padding: ScreenUtil.scaleSize(10)
    }
});

The complete project is located in: GitHub

Tags: React github

Posted on Sat, 21 Mar 2020 09:12:21 -0700 by Julian