0

Hi everyone and sorry for maybe this dumb question, i'm working with javascript modules and trying to organize everything in order to be easier to use for my jr programmers since we are all kinda new to javascript not Jquery framework programming, so the thing is:

I created a module which is a helper for fetch data from rest services called Router:

const BaseUrl = 'http://localhost:1128'

/**
 * 
 * Falta Mejorar la función para los siguientes escenarios:
 * 1) Que se elija la ruta desde un modulo que tenga ya prefabricadas las rutas
 * 2) Para establecer un timeout
 * 3) que pasa con los CData y el envio de archivos
 * 4) Hay que validar los casos genericos donde se envia informacion al servidor como datos de usuario contraseña y Json Token
 */

async function request(url, params, method = 'GET') {
    //los parametros que le vamos a enviar al fetch
    const options = {
        method,
        headers: {
            'Content-Type': 'application/json' // we will be sending JSON
        }
    };

    //solo para el get enviaremos los parametros por url, si es otro lo enviaremos por el body
    if (params) {
        if (method === 'GET') {
            //url += '?' + objectToQueryString(params);
            url += '/' + params;
        } else {
            options.body = JSON.stringify(params); // body should match Content-Type in headers option
        }
    }

    //esperamos a que la promesa termine para poder ejecutarlo, fetch es una promesa

    let result;
    try {
        const response = await fetch(BaseUrl + url, options);
        if (response.status !== 200) {
            result = generateErrorResponse('Ocurrió un error.', response.status);
        }
        result = await response.json(); // convertimos el resultado en json
    }
    catch (e) {
        result = generateErrorResponse(e.message, 500);
    }
    return result;
}

function generateErrorResponse(message, status) {
    return {
        codigo: 'error',
        message,
        status
    };
}

function get(url, params) {
    return request(url, params);
}

function create(url, params) {
    return request(url, params, 'POST');
}

function update(url, params) {
    return request(url, params, 'PUT');
}

function remove(url, params) {
    return request(url, params, 'DELETE');
}

//Convierte el objeto en parametros para la url (solo para el caso del get)
function objectToQueryString(obj) {
    return Object.keys(obj).map(key => key + '=' + obj[key]).join('&');
}

export default {
    get,
    create,
    update,
    remove
};

Then i created another module which uses the router to fetch data from specific url and retrieve Json formated data from it, the module is this:

import RouterModule from './RouterModule.js'
import GetListOptions from './Helpers/HtmlHelpers.js'
const relativeUrl = "/personas"

export async function ObtenerSelectPersonasAsync(UsuarioId, htmlSelectObj) {
    try {

        const ResponseArray = await RouterModule.get(relativeUrl, UsuarioId !== 0 ? UsuarioId : null)
        const ListOptions = GetListOptions(ResponseArray, 'personaId', 'nombre', '3', htmlSelectObj)
        return ListOptions;
    }
    catch (e) {
        return {
            error: 'Error',
            status: 404

        }
    }
}

export async function ObtenerPersonas(UsuarioId) {
    try {

        const ResponseArray = await RouterModule.get(relativeUrl, UsuarioId !== 0 ? UsuarioId : null)
        return ResponseArray;
    }
    catch (e) {
        return {
            error: 'Error',
            status: 404

        }
    }
}


export default {
    ObtenerPersonas,
    ObtenerSelectPersonasAsync
}

So the final programmer just needs to use the PersonasModule in order to work with database (this is in my mind, please correct me if i'm doing something wrong),

So in index.html they just need to this:

<script type="module">
    import { ObtenerSelectPersonasAsync, ObtenerPersonas } from './JsModules/PersonasModule.js';
    let Persona = ObtenerPersonas(1) //here it's supposed to retrieve an array however im getting a promise
Persona.then(result => {
        inputNombre.value = result[0].nombre;

    })
</script>

can you please tell me why is this happening, am i missing something? maybe i'm doing some nasty stuff and there is a better way to do this, if you can guide me in the right way i'll be grateful, thank you so much.

thepanch
  • 353
  • 2
  • 13
  • Does the `Persona.then(result => { inputNombre.value = result[0].nombre; })` result in the value being assigned? It looks like that should work – CertainPerformance Mar 14 '20 at 06:19
  • 1
    `ObtenerPersonas` is an async function, which means it returns a promise. – MjZac Mar 14 '20 at 06:21
  • @CertainPerformance yes, the code works well, but what i'm triying to avoid the use of promises at the very end, to get the right objects – thepanch Mar 14 '20 at 06:24
  • @MjZac Is there a way to avoid it? to make it work like a regular function? – thepanch Mar 14 '20 at 06:24
  • No, the value is retrieved asynchronously, so the consumer can't use it synchronously - you're doing it properly – CertainPerformance Mar 14 '20 at 06:25
  • @MjZac you must wait for promise to resolve – Prakash Reddy Potlapadu Mar 14 '20 at 06:25
  • No. One thing you can do is change the signature of the function to accept a callback, which will be invoked after network request completes. But that again is just going back to dark ages of call back hell. – MjZac Mar 14 '20 at 06:27
  • is there a way to wait the promise to be excecuted on the ObtenerPersonas function so the new programmers don't need to play with promises and stuff because that could be a problem – thepanch Mar 14 '20 at 06:29
  • Since promises is baked into Js, it should not be a hassle for new programmers to use it. What you are asking is the way how it was done before introducing `Promises`. I can show a way by making use of callback. – MjZac Mar 14 '20 at 06:36
  • It would be something like `export function ObtenerPersonas(UsuarioId, callback) { ... RouterModule.get(..).then((responseArray) => {return callback(responseArray)}}` – MjZac Mar 14 '20 at 06:38
  • would it be possible to add an await keyword in the promise execution on the main html and just wrap it in a async funtion? that would be easier – thepanch Mar 14 '20 at 06:44

0 Answers0