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);
    })();
  • 相关阅读:
    程序员的希波克拉底誓言[精华]
    怎样成为优秀的软件模型设计者
    C#中Delegate浅析与思考
    程序员是一个美好的职业[精华]
    hdu 1421(搬寝室)
    hdu 4022(map一对多)
    hdu 1114(完全背包)
    hdu 1159(最长公共子序列)
    hdu 2844(多重背包)
    hdu 1257(最长递增子序列)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6805060.html
Copyright © 2011-2022 走看看