[Javascript] Run asynchronous functions in sequence using reduce

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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: [ … ]

 

以上是关于[Javascript] Run asynchronous functions in sequence using reduce的主要内容,如果未能解决你的问题,请参考以下文章

如何使用纯 JavaScript 在 grunt-run qunit 测试中触发 TouchEvent?

WebView JavaScript 接口似乎只能通过 Android Studio 的 Instant-Run 工作,但不能通过常规 gradle 编译

javascript 智利DNI验证器并获取JSON {run:Number / String,adv:Number / String,dv:Number / String,valid:Boolean

异步等待失败 swift API 请求

javascript 面向对象

javascript 工厂模式