zoukankan      html  css  js  c++  java
  • [ES7] Handle Errors in Asynchronous Functions

    This lesson shows how regular control flow statements such as try/catch blocks can be used to properly handle errors in asynchronous functions. Oftentimes, the resulting code is easier to read than complex promise chains with .catch()methods.

    const fetch = require('node-fetch');
    const BASE_URL = 'https://api.github.com/users';
    
    class GithubUser {
        async fetchGitHubUser(handle) {
            const response = await fetch(`${BASE_URL}/${handle}`);
            const body =  await response.json();
    
            if (response.status !== 200) {
                throw Error(body.message);
            }
    
            return body;
        }
    }
    
    (async () => {
        const github = new GithubUser();
    
        try {
            const user = await github.fetchGitHubUser('zhentian-wan');
            console.log(user);
        } catch(err) {
            console.error(err);
        }
    
    
    })();
  • 相关阅读:
    抽象工厂模式
    工厂方法模式
    简单工厂模式
    Zuul
    Turbine
    Hystrix
    Feign
    Ribbon
    Eureka
    @MappedSuperclass的作用
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6805062.html
Copyright © 2011-2022 走看看