0

I have had a problem for several days. I have the following class that returns an object from the backend.

export default class ProductResponseBarCode {

async loadProduct(urlList, inputValue, callback) {
        return fetch(urlList, {
            method: "POST",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                CodigoNombre: inputValue,
                length: 1,
                pageNumber: 1
            })
        }).then(response => {

            if (!response.ok) {
                throw new Error(response.statusText)
            }

            return response.json();
        }).then(result => {
            switch (result.accion) {
                case 'success':
                    if (result.Lista.length > 0) {

                        return JSON.parse(JSON.stringify(result.Lista[0]));
                        
                    } else {
                        swal({
                            title: 'Error de operaci\u00f3n',
                            text: "Producto no existe",
                            type: 'error'
                        });
                    }
                    break;
                case 'error':

                    swal({
                        title: 'Error de operaci\u00f3n',
                        text: result.Msj,
                        type: 'error'
                    });
                    break;
            }
        }).catch(error => {
            swal({
                title: 'Request Failed',
                text: error,
                type: 'error'
            })
        });
}

and I have another class where I call this method but using the setTimeout function

export default class BarcodeReader{

static input;

constructor() {
        this.notEnterBarcodeTimeout = null;
    }

readCode(event) {

        if (this.notEnterBarcodeTimeout) {
            window.clearTimeout(this.notEnterBarcodeTimeout);
        }

        if (event.key === 'Enter') {
            BarcodeReader.prototype.loadProductWithBarcode();
        } else {
            this.notEnterBarcodeTimeout = setTimeout(() => {
                let object = BarcodeReader.prototype.loadProductWithBarcode();
                console.log(object);
            }, 1000);
        }

    }

async loadProductWithBarcode() {
        if (BarcodeReader.input.value === "") {
            swal({
                title: 'Error de operaci\u00f3n',
                text: "Producto no leido",
                type: 'error'
            });
        } else {
            BarcodeReader.i++;
            const test = await ProductResponseBarCode.prototype.loadProduct(BarcodeReader.urllistProduct, BarcodeReader.input.value);
            BarcodeReader.input.value = '';
            return test;
        }
        
    }
setBarcodeReader(button) {
        if (!this.init) {
            const inputDom = document.querySelector('.js-barcode-input');
            BarcodeReader.button = button;
            BarcodeReader.input = inputDom;
        }
        const inputDom = BarcodeReader.input;
        if (!this.state) {
            this.state = true;
            button.classList.add('focus');
            inputDom.addEventListener('keyup', this.readCode, false);
            inputDom.focus();
            inputDom.addEventListener('focusout', this.setBarCodeReaderOFF);
        } else {
            this.state = false;
            button.classList.remove('focus');
            inputDom.removeEventListener('keyup', this.readCode, false);
            inputDom.removeEventListener('focusout', this.setBarCodeReaderOFF, false);
            inputDom.blur();
            button.blur();
        }
    }

}

what I do is that I execute the readCode method when the keyup event is fired but when I see the BarcodeReader.prototype.loadProductWithBarcode() method console it shows me the following

enter image description here

  • Wait for the promise to resolve with `async`/`await` or chain a `then` call. – kelsny Aug 15 '22 at 20:32
  • Hello and thanks for answering what do you mean that I do in my methods or what am I doing wrong – Jonathan Cunza Aug 15 '22 at 20:38
  • 1
    `loadProductWithBarcode()` is an `async` function and ALL `async` functions return a promise. If the caller wants to know when they are done or wants to know what their resolved value is, then the caller must use `await` or `.then()` to know that. And, the `return` inside `loadProductWithBarcode()` happens BEFORE the promise is resolved so the caller will initially see the promise as pending. – jfriend00 Aug 15 '22 at 21:00
  • Thanks for commenting I don't understand the `then()` that you mention where I should place it – Jonathan Cunza Aug 15 '22 at 21:16

1 Answers1

1

loadProductWithBarcode returns a Promise. You can await the promise like such obj = await BarcodeReader.prototype.loadProductWithBarcode() but this only works in a function that is marked as async (such as async loadProductWithBarcode(). You also used await in there.

To me it seems that .then would be easier in your case:

BarcodeReader.prototype.loadProductWithBarcode().then(object => {
    console.log(object);
});

However, .then() can be just as messy as callbacks

async readCode(event) {

    if (this.notEnterBarcodeTimeout) {
        window.clearTimeout(this.notEnterBarcodeTimeout);
    }

    if (event.key === 'Enter') {
        let object = await BarcodeReader.prototype.loadProductWithBarcode();
        console.log(object);
    } else {
        this.notEnterBarcodeTimeout = setTimeout(async () => {
            let object = await BarcodeReader.prototype.loadProductWithBarcode();
            console.log(object);
        }, 1000);
    }

}
HEllRZA
  • 287
  • 1
  • 7