f-async-resolver
v0.0.1
Published
Make your functions async without the need of doing it in the same Function
Downloads
2
Maintainers
Readme
f-async-resolver
Make your functionas async.
This module is made so you can make your funcions async and return a value without the need of having it in the same function. For example returning an answer from a server in a WebSocket connection.
Installing
npm i f-async-resolver
Initializing
const async = require('f-async-resolver').resolver;
const resolver = new async();
Examples
Awaiting for a Number
const async = require('f-async-resolver');
const resolver = new async.resolver();
function number() {
return new Promise(solver => {
resolver.await('number', solver);
});
}
number.then(number => {
console.log(number);
});
setTimeout(() => {
resolver.resolve('number', 15);
}, 1000);
/*
Output (1 Second after running the Code)
> 15
*/
Awaiting for WebSockets message.
const async = require('f-async-resolver');
const resolver = new async.resolver();
const WebSocket = require('ws');
class database {
constructor(IP) {
this.ws = new WebSocket('ws://127.0.0.1:4000'); // Connects to a Server.
this.ws.onopen = this.onopen.bind(this); // Simple function Bind.
this.ws.onmessage = this.onmessage.bind(this); // Simple function Bind.
}
onopen() {
console.log('Connected!');
}
get() {
return new Promise(solver => { // Returns a Promise and makes 'solver' to solve.
this.ws.send({
type: 'getDatabase'
}); // Sends a message to the Server
resolver.await('getDB', solver); // Sets label and function to Solve.
});
}
onmessage(msg) {
resolver.resolve('getDB', msg); // Solves 'getDB' label with msg value.
}
};
const connection = new database('ws://127.0.0.1:4000');
connection.get().then(msg => {
console.log('Awaited for ' + msg); // Shows the message Recieved.
});