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);
    })();
  • 相关阅读:
    js中new的本质
    js中真伪数组转换
    2 DC电参数测试 (1)
    1 开短路测试
    2月书单 《编码隐匿在计算机软硬件背后的语言》 21-25章
    2月书单 《编码隐匿在计算机软硬件背后的语言》 17-20章
    时间的掌控
    数码管的秘密
    会眨眼的小灯
    点亮一盏灯
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6805060.html
Copyright © 2011-2022 走看看