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);
    })();
  • 相关阅读:
    2021.12.7
    2021.12.13(观察者模式c++)
    2021.12.05(echarts生成mysql表词云)
    2021.12.10(申请加分项)
    2021.12.10(课程总结)
    2021.12.11(Linux,yum错误,There are no enabled repos.)
    12月读书笔记02
    2021.12.12(springboot报ScannerException)
    2021.12.09
    centos国内镜像站
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6805060.html
Copyright © 2011-2022 走看看