Skip to content

Instantly share code, notes, and snippets.

@lmzach09
Last active September 2, 2019 17:42
Show Gist options
  • Select an option

  • Save lmzach09/66a45353ccd150257ad3547f706e4e3c to your computer and use it in GitHub Desktop.

Select an option

Save lmzach09/66a45353ccd150257ad3547f706e4e3c to your computer and use it in GitHub Desktop.
Implementation of a for-each loop in JavaScript that works with callbacks. The next iteration in the loop does not start until the previous iteration's callback gets called.
// request method implementation is in a GitHub Gist linked below
const array = [1, 2, 3, 4, 5];
array.forEachWithCallback((el, i, next) => {
request({
method: 'GET',
hostname: 'httpbin.org',
path: '/get?myArg=' + el
}).then((res) => {
const responseBody = JSON.parse(res.body);
console.log(responseBody.args.myArg);
next();
}).catch((err) => {
console.error(err);
});
});
@lmzach09

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment