DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,274 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for ES7 Async/Await with React Native
Dale L. Jefferson
Dale L. Jefferson

Posted on • Updated on • Originally published at dalejefferson.com

ES7 Async/Await with React Native

Async/Await is a new syntax for writing asynchronous code in JavaScript. Support was added in React Native 0.10 and it’s now reached TC39 stage 3 (candidate).

Example

In this example using the promise returning fetch polyfill. We will display the React Native GitHub star count.

const URL = "https://api.github.com/repos/facebook/react-native";

class StarCount extends Component {
  constructor() {
    super();

    this.state = {stars: "?"};
  }

  componentDidMount() {
    this.fetchData().done();
  }

  async fetchData() {
    const response = await fetch(URL);
    const json = await response.json();
    const stars = json.stargazers_count;

    this.setState({stars});
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.text}>
          React Native has {this.state.stars} stars
        </Text>
      </View>
    );
  }
}

Async / await works with any Promise based API or one of your creation.

const getStars = () =>
  new Promise(resolve => {
    const FIVE_SECONDS = 5000;
    // Simulate async operation
    setTimeout(() => resolve(1234), FIVE_SECONDS);
  });
const fetchData = async () => {
  const stars = await getStars();
  // Do something with stars
};

Top comments (0)

Classic DEV Post from 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!