LoginSignup
11
4

More than 5 years have passed since last update.

Array.reduceとasync/awaitを使って関数を順番に実行する

Last updated at Posted at 2018-06-24

Array.reduce()を使う

const axios = require('axios');

// https://qiita.com/asa-taka/items/888bc5a1d7f30ee7eda2
const sleep = msec => new Promise(resolve => setTimeout(resolve, msec));

const users = [
    'tj',
    'dougwilson',
    'jonathanong',
    'defunctzombie',
    'aheckmann',
    'slaskis',
    'ciaranj',
    'michaelahlers',
    'blakeembrey',
    'notrab',
    'riadhchtara'
];

async () => {
    const names = await users.reduce(async (prev, user) => {
        try {
            const p = await prev;
            const { data } = await axios.get(`https://api.github.com/users/${user}`);
            // rate limit対策
            await sleep(1000);
            return [...p, data];
        } catch (err) {
            console.log(err);
        }
    }, []);
};
11
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
4