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