Right, just so it's out the way, I'm new to JS and Espruino and so got stuck during a project; I'm trying to get the max of an array to be console.logged just after the main function is executed:
const cw = 1;
const ccw = 0;
const dataCW = [];
const peekCW = [];
const dataCCW = [];
const peekCCW = [];
const dataLength = 36;
const getData = (dir, t, fn) => {
const solarIn = () => analogRead(A5);
const dataRead = () => ((solarIn() * 65536) * 5.0) / 65536;
const dataPush = (data) => {
data.push(dataRead());
};
const peekVal = (fnc) => {
if(dir === 1) {
for(let i = 0; i < dataLength; i++) {
setTimeout(() => {
dataPush(dataCW);
if(dataCW.length === dataLength) {
let peekValCW = Math.max.apply(null, dataCW);
let peekValPosCW = dataCW.indexOf(peekValCW);
peekCW.push(peekValPosCW);
}
}, i * (t / dataLength));
}
}
else if(dir === 0) {
for(let i = 0; i < dataLength; i++) {
const forCCW = setTimeout(() => {
dataPush(dataCCW);
if(dataCCW.length === dataLength) {
let peekValCCW = Math.max.apply(null, dataCCW);
let peekValPosCCW = dataCCW.indexOf(peekValCCW);
peekCCW.push(peekValPosCCW);
}
}, i * (t / dataLength));
}
}
fnc();
};
fn(peekVal, peekCW);
};
getData(cw, 1000, (n, m) => n((m) => console.log(m)));
I feel I've spent way too much time trying on my own and only got frustrated with returns like undefined
or = [ ]
because I can't pass it properly after the function's done executing. Honestly I'm only interested in resolutions involving callbacks, I know Espruino now has Promises implemented and all but feel that this needs to be done with callbacks as I feel this is such an important topic to know/master. Thanks for you help.
Regards, George M.