Last active
January 25, 2018 23:43
-
-
Save grantholle/285ecba9ed08de0544f7d4288365d119 to your computer and use it in GitHub Desktop.
async loop
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
// This will make the requests one at a time, not all at once, | |
// but everything after will still be called because it's async | |
// add tags to post | |
const tags = post.tags | |
post.tagNames = [] | |
const loop = i => { | |
const tagnum = tags[i] | |
rp(tagUrl + tagnum).then(data => { | |
if (data) { | |
var x = JSON.parse(data) | |
post.tagNames.push(x.name) | |
} else { | |
return new error('failed to get tag names') | |
} | |
if (tags[i + 1]) { | |
loop(++i) | |
} | |
}) | |
} | |
loop(0) | |
// This will be blocking, so anything after calling getTagNames | |
// will not be executed | |
const getTagNames = tags => { | |
const tagNames = [] | |
return new Promise((resolve, reject) => { | |
const loop = i => { | |
const tagnum = tags[i] | |
rp(tagUrl + tagnum).then(data => { | |
if (data) { | |
var x = JSON.parse(data) | |
tagNames.push(x.name) | |
} else { | |
return reject(new error('failed to get tag names')) | |
} | |
if (tags[i + 1]) { | |
loop(++i) | |
} else { | |
resolve() | |
} | |
}) | |
} | |
loop(0) | |
}) | |
} | |
// Get the names, then do something afterwards | |
getTagNames(post.tags).then(names => { | |
post.tagNames = names | |
}) | |
// Or using async/await, which is the cleanest IMO | |
// The function this is in has to be async | |
const getTagNames = async tags => { | |
const tagNames = [] | |
for (var i = 0; i < tags.length; i++) { | |
const tagnum = tags[i] | |
let data | |
try { | |
// This is the magic that makes it blocking | |
data = await rp(tagUrl + tagnum) | |
} catch (err) { | |
throw err | |
} | |
if (data) { | |
var x = JSON.parse(data); | |
tagNames.push(x.name); | |
} else { | |
throw new error('failed to get tag names'); | |
} | |
} | |
return tagNames | |
} | |
// Do something | |
post.tagNames = getTagNames(post.tags) | |
// This won't happen until the above is finished |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment