Skip to content

Instantly share code, notes, and snippets.

@lxynox
Created September 24, 2019 03:03
Show Gist options
  • Save lxynox/2e19a2993222adc0b6e7321c90d514a3 to your computer and use it in GitHub Desktop.
Save lxynox/2e19a2993222adc0b6e7321c90d514a3 to your computer and use it in GitHub Desktop.
Resolve promises one after another (i.e. in sequence)

asycn/await

async function readFiles(files) {
  for(const file of files) {
    await readFile(file);
  }
};

yield

async function* readFiles(files) {
  for(const file of files) {
    yield await readFile(file);
  }
}

forEach

function readFiles(files) {
  let p = Promise.resolve()
  files.forEach(f => {
    p = p.then(() => readFile(f))
  })
  return p
}

reduce

Or more succinct,

function readFiles(files) {
  return files.reduce((p, f) => {
    return p.then(() => readFile(f))
  }, Promise.resolve())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment