zoukankan      html  css  js  c++  java
  • [Javascript] Run asynchronous functions in sequence using reduce

    This can be handy if you have a rate limit on API requests or if you need to pass the result of each promise to the next one. 

    function fetchMessages(username) {
        return fetch(`https://example.com/api/messages/${username}`)
            .then(response => response.json());
    }
    
    function getUsername(person) {
        return person.username;
    }
    
    async function chainedFetchMessages(p, username) {
        // In this function, p is a promise. We wait for it to finish,
        // then run fetchMessages().
        const obj  = await p;
        const data = await fetchMessages(username);
        return { ...obj, [username]: data};
    }
    
    const msgObj = peopleArr
        .map(getUsername)
        .reduce(chainedFetchMessages, Promise.resolve({}))
        .then(console.log);
    // ⦘ {glestrade: [ … ], mholmes: [ … ], iadler: [ … ]}
  • 相关阅读:
    弹性布局、动画、过渡
    HTML
    数据库对象
    函数
    oracle与PL/SQL安装
    网络编程
    多线程
    联调接口
    vue 全局变量
    vue ajax请求
  • 原文地址:https://www.cnblogs.com/Answer1215/p/11452370.html
Copyright © 2011-2022 走看看