zoukankan      html  css  js  c++  java
  • [ES7] Convert Any Function into an Asynchronous Function

    Any function can be made asynchronous, including function expressions, arrow functions, and methods. This lesson shows the syntax for each of the function types.

    For example, we have a demo:

    const fetch = require('node-fetch');
    const BASE_URL = 'https://api.github.com/users';
    
    const fetchGitHubUser = async (handle) => {
        const response = await fetch(`${BASE_URL}/${handle}`);
        return await response.json();
    };
    
    fetchGitHubUser('zhentian-wan')
        .then(console.log)

    Since 'fetchGithubUser' is also an async function, we can convert it to async/await function:

    const fetch = require('node-fetch');
    const BASE_URL = 'https://api.github.com/users';
    
    const fetchGitHubUser = async (handle) => {
        const response = await fetch(`${BASE_URL}/${handle}`);
        return await response.json();
    };
    
    (async () => {
        const user = await fetchGitHubUser('zhentian-wan');
        console.log(user);
    })();

    Here we must wrap await function inside IIFE async function, otherwise it won't work.

    We can also convert 'fetchGithubUser' function into a class:

    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}`);
            return await response.json();
        }
    }
    
    (async () => {
        const github = new GithubUser();
        const user = await github.fetchGitHubUser('zhentian-wan');
        console.log(user);
    })();
  • 相关阅读:
    CentOS7.6安装Kubernetes v1.15.1
    数据库三大范式
    linux
    linux
    linux
    linux
    Django contenttypes组件
    Django自带的用户认证
    Django rest framework(7) ---分页
    Django rest framework(6) ---序列化
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6805060.html
Copyright © 2011-2022 走看看