I have these water names and I want that putting an input with a water name, the promise will return me a result. The problem is that it doesn't return anything, how can I fix it?
const water = [
{ nome: "Sant'anna", inStore: true },
{ nome: "Levissima", inStore: false },
{ nome: "Lete", inStore: true },
];
let inStoreTrue = [];
let inStoreFalse = [];
water.forEach(({ nome, inStore }) => {
if (inStore === true) {
inStoreTrue.push({ nome });
} else {
inStoreFalse.push({ nome });
}
});
function checkWater(enter) {
return new Promise((resolve, reject) => {
if (enter === inStoreTrue) {
resolve("la tua acqua è disponibile");
} else if (enter === inStoreFalse) {
reject("La tua acqua non è disponibile");
}
});
}
let prom = checkWater("Sant'anna");
prom
.then((risultato) => {
console.log(risultato);
})
.catch((err) => {
console.log(err);
});
The issue is with checking enter === inStoreTrue and enter === inStoreFalse
inStoreTrue and inStoreFalse are arrays. So you cannot simply equate a string with an array. You have to check whether the string is there in the array with some array methods. I used Array.some for that.
const water = [
{ nome: "Sant'anna", inStore: true },
{ nome: "Levissima", inStore: false },
{ nome: "Lete", inStore: true },
];
let inStoreTrue = [];
let inStoreFalse = [];
water.forEach(({ nome, inStore }) => {
if (inStore === true) {
inStoreTrue.push({ nome });
} else {
inStoreFalse.push({ nome });
}
});
function checkWater(enter) {
return new Promise((resolve, reject) => {
if (inStoreTrue.some((item) => item.nome === enter)) {
resolve("la tua acqua è disponibile");
} else if (inStoreFalse.some((item) => item.nome === enter)) {
reject("La tua acqua non è disponibile");
}
});
}
let prom = checkWater("Sant'anna");
prom
.then((risultato) => {
console.log(risultato);
})
.catch((err) => {
console.log(err);
});