Last active
September 2, 2019 18:36
-
-
Save lmzach09/50a731747ed39f25c8e1558aa4f63a4b to your computer and use it in GitHub Desktop.
An example of a for-each loop implementation with callbacks using the async/await pattern. This works in the browser and Node.js. Get the "request" method here https://gist.github.com/lmzach09/38d291edb90f64d338132824a9de35ce#file-request-js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const request = require('./request.js'); | |
function forEachWithCallback(callback) { | |
const arrayCopy = this; | |
let index = 0; | |
const next = () => { | |
index++; | |
if (arrayCopy.length > 0) { | |
callback(arrayCopy.shift(), index, next); | |
} | |
} | |
next(); | |
} | |
Array.prototype.forEachWithCallback = forEachWithCallback; | |
const array = [1, 2, 3, 4, 5]; | |
array.forEachWithCallback(async (el, i, next) => { | |
const response = await request({ | |
method: 'GET', | |
hostname: 'httpbin.org', | |
path: '/get?myArg=' + el | |
}); | |
const responseBody = JSON.parse(response.body); | |
console.log(responseBody.args.myArg); | |
next(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment