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);
    })();
  • 相关阅读:
    根据用户行为发送客服消息
    tp5链接访问
    统计每天分享次数总和
    csv中文乱码
    Jupyter Notebook命令
    Laplace(拉普拉斯)算子
    Sobel算子
    Opencv图像连通域
    Opencv常用函数讲解
    12306 Pytho抢票代码
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6805060.html
Copyright © 2011-2022 走看看