paranymph-sync
v1.0.0
Published
JavaScript μ function to execute functions synchronously and return result when all callbacks are done
Downloads
1
Readme
paranymph-sync
Function
const paranymphSync = (list, callback) => {
(function loop(list, callback, i, result) {
list[i]((err, data) => {
return list[++i] && !err ? loop(list, callback, i, data) : callback(err, data)
}, result)
})(list, callback, 0)
}
Minification
const paranymphSync = (l,c) => (function $(l,c,i,r){l[i]((e,d)=>l[++i]&&!e?$(l,c,i,d):c(e,d),r)})(l,c,0)
Speed test paranymphSync vs async.waterfall in node.js
Requesting findOne to MongoDB
setTimeout test synchronously
paranymphSync([
callback => setTimeout(() => callback(null, 1), 500),
(callback, result) => setTimeout(() => callback(500, 'Some error'), 200),
(callback, result) => setTimeout(() => callback(null, result*2), 50)
], (err, data) => console.log('Callback with error: => ', err, data))
result
Callback with error: => 500 Some error
paranymphSync([
callback => setTimeout(() => callback(null, 1), 500),
(callback, result) => setTimeout(() => callback(null, result*2), 200),
(callback, result) => setTimeout(() => callback(null, result*2), 50)
], (err, data) => console.log('Callback without error: => ', err, data))
result
Callback without error: => null 4
XMLHttpRequest test synchronously
paranymphSync([
(callback) => {
//Get time
const req = new XMLHttpRequest()
req.onload = () => callback(null, JSON.parse(req.responseText))
req.onerror = () => callback(true, req.status)
req.ontimeout = () => callback(true, req.status)
req.open('GET', 'http://time.jsontest.com/')
req.send()
},
(callback, result) => {
//Hash time
const req = new XMLHttpRequest()
req.onload = () => callback(null, JSON.parse(req.responseText))
req.onerror = () => callback(true, req.status)
req.ontimeout = () => callback(true, req.status)
req.open('GET', 'http://md5.jsontest.com/?text='+result.time)
req.send()
},
(callback, result) => {
//Create value
const req = new XMLHttpRequest()
req.onload = () => callback(null, JSON.parse(req.responseText))
req.onerror = () => callback(true, req.status)
req.ontimeout = () => callback(true, req.status)
req.open('GET', ' http://echo.jsontest.com/hashtime/'+result.md5)
req.send()
}
], (err, data) => console.log(err, data))
result
null Object {hashtime: "e75923f1ef2977abf5ebc988a40a188b"}