码迷,mamicode.com
首页 > 编程语言 > 详细

[Javascript] Run asynchronous functions in sequence using reduce

时间:2019-09-03 13:40:35      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:fetch   rom   sage   amp   result   chm   res   com   mes   

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

标签:fetch   rom   sage   amp   result   chm   res   com   mes   

原文地址:https://www.cnblogs.com/Answer1215/p/11452370.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!