Skip to content

Instantly share code, notes, and snippets.

@dsngo
Forked from istarkov/serialize.js
Created February 24, 2023 09:54
Show Gist options
  • Save dsngo/e13e81d13c2b0c4544b023433c9cfd74 to your computer and use it in GitHub Desktop.
Save dsngo/e13e81d13c2b0c4544b023433c9cfd74 to your computer and use it in GitHub Desktop.
Serialize promise calls (run promises sequentially)
// promise
const sleep = (timeout, v) => new Promise(r => setTimeout(() => r(v), timeout));
// series to call
const series = [() => sleep(1000, 1), () => sleep(1000, 2), () => sleep(1000, 3)];
// serialize
const r = series
.reduce(
(m, p) => m.then(v => Promise.all([...v, p()])),
Promise.resolve([])
);
// get result
r.then((r) => console.log('done', r))
// out [1, 2, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment