Skip to content

Instantly share code, notes, and snippets.

@marekdano
Created May 31, 2019 15:32
Show Gist options
  • Save marekdano/533043f3cc895df8e0845dbb1ae5727a to your computer and use it in GitHub Desktop.
Save marekdano/533043f3cc895df8e0845dbb1ae5727a to your computer and use it in GitHub Desktop.
Run asynchronous functions in sequence
// Run asynchronous functions in sequence
const peopleArr = [
{
username: 'glestrade',
displayname: 'Inspector Lestrade',
email: '[email protected]',
authHash: 'bdbf9920f42242defd9a7f76451f4f1d',
lastSeen: '2019-05-13T11:07:22+00:00',
},
{
username: 'mholmes',
displayname: 'Mycroft Holmes',
email: '[email protected]',
authHash: 'b4d04ad5c4c6483cfea030ff4e7c70bc',
lastSeen: '2019-05-10T11:21:36+00:00',
},
{
username: 'iadler',
displayname: 'Irene Adler',
email: null,
authHash: '319d55944f13760af0a07bf24bd1de28',
lastSeen: '2019-05-17T11:12:12+00:00',
},
];
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: [ … ]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment