After much reading the comments and links of:
@Bergi
@TheMaster
@Thomas
I think I have found the best solution I hope I am not wrong, if I am, I hope it is not too much to ask that the people who respond, do so with the intention of solving the problem instead of just pointing out an error or that something does not like.
"Please, show me the code! " instead ;)
This is a example of the dumbest way to split a String
using eventEmitter, async await and this aproach and Works!
let event = new(require('events').EventEmitter);
async function split(string) {
let holder = {};
let promise = async() => {
return await (holder.payload || holder.error) ? holder : null;
}
event.on('done', data => done(data));
function done(data) {
try {
console.log('Done emitted');
console.log(`Param: ${data}`);
holder.payload = data;
} catch(error) {
console.log(error);
}
}
event.on('error', error => fail(error));
function fail(error) {
try {
console.log('Fail emitted');
console.log(`Param: ${error}`);
holder.error = error;
} catch(error) {
console.log(error);
}
}
event.on('split', async(string) => {
try {
console.log('Split emitted');
console.log(`Param : ${string}`);
const data = string.split(' ');
event.emit('done', data);
} catch(error) {
console.log(error);
event.emit('error', error);
}
});
try {
event.emit('split', string);
return({ payload: await promise().then(data => { return data.payload }) });
} catch(error) {
console.log(error);
}
}
console.clear()
console.log(
split('Hello world').then(data => {
console.log('Split done!');
console.log(data);
})
);
So at this point var 'holder' and function 'promise'
are inside the scoop of the function 'split' and all the console outputs are:
Split emitted
Param : Hello world
Done emitted
Param: Hello,world
Promise { <pending> }
Split done!
{ payload: [ 'Hello', 'world' ] }
The whole point is to ilustrate that it is possible to have n asynchronous events, callbacks and promises
and be able to return a value, after a process of n stages or events
thanks for your time guys, and any other comments, sorry for any mistakes.