I'm trying to run two functions that run a promise. The first one, comprobar_datos_login(), is run. But the second one, guardar_sesion(), isn't run.
Here is the code:
document.getElementById("ini_sesion").onclick = function() { ejecutar() };
function comprobar_datos_login() {
const fichero = "/scripts/usr.php";
email = document.getElementById("correo").value;
contrasena = document.getElementById("contrasenya").value;
let resposta = fetch(fichero, {
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({correu:email,clau:contrasena})
})
.then(resposta => resposta.text())
.then(resposta => {
let resultado = resposta;
let datos;
let url_path;
switch (resultado) {
case "Debes llenar todos los campos":
document.getElementById("missatges").textContent = "Debes llenar todos los campos";
break;
case "Campos vacios":
document.getElementById("missatges").textContent = "Campos vacíos";
break;
default:
datos = JSON.parse(resultado);
}
})
.catch(error => alert("Error" + error));
}
function guardar_sesion() ´{
const ficheroSesion = "/scripts/usr_sesion.php";
let respuesta = fetch(ficheroSesion, {
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({correo_usr: email,nombre_usr: nomusr,apellido_usr: cognomusr})
})
.then(respuesta => respuesta.text())
.then(respuesta => {
console.log("sesion guradada");
})
.catch(error => alert("Error " + error));
}
function ejecutar() {
return comprobar_datos_login()
.then((resul) => guardar_sesion(resul));
}
I checked this question but I couldn't get a solution.
I don't know what is wrong. How can the second function be run?
Thanks
Related
const init = () => {
document.querySelector("#newTask").addEventListener("click", addNewTask);
//document.querySelector("#deleteTask").addEventListener("click", deleteData);
getDataa();
};
const getDataa = () => {
addNewTask();
const url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/2877332";
fetch(url, {
method: "GET",
withCredentials: true,
headers: {
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
"Content-Type": "application/json"
}
})
.then(resp => resp.json())
.then(function(data) {
console.log(data);
// Loop to access all rows
for (i = 0; i <= data.ScannedCount; i++) {
let text = "";
//const items = data.Items[i].Description;
Array.from(data.Items).forEach(myFunction);
// display the data to the end user and link it to the index page
document.getElementById("displayTable").innerHTML = text;
function myFunction(item, index) {
text += ' <button type="button" class="btn" id="task" onclick="deleteData()"><i class="fa fa-trash"></i></button>' + " " + data.Items[index].Description + "<br>";
}
}
})
.catch(function(error) {
console.log(error);
});
}
const deleteData = () => {
console.log("delete data ");
//let deleteDescription = document.querySelector("#task").value;
let xhr = new XMLHttpRequest();
let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks/";
let studentId = "2877332";
let taskDescription = document.querySelector("#task").value;
fetch(url, {
method: 'DELETE',
headers: {
"Content-Type": "application/json",
"x-api-key": "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S",
},
body: {
'StudentId': 'studentId',
'Description': 'taskDescription',
'version': 'JSON',
}
})
.then(res => {
if (res.ok) {
console.log("DELETE request successful");
getDataa();
return res
} else {
console.log("DELETE request unsuccessful");
}
return res
})
.then(res => res.json())
.then()
.catch(error => console.log(error))
}
const addNewTask = () => {
console.log("Adding a new task...");
let xhr = new XMLHttpRequest();
let url = "https://ghu8xhzgfe.execute-api.us-east-1.amazonaws.com/tasks";
let apiKey = "Itcheui2tB58SlUGe8rrP8mskudGsNDT9nfKKG9S";
let studentId = "2877332";
let taskDescription = document.querySelector("#task").value;
let params = {
StudentId: studentId,
Description: taskDescription
};
xhr.open("post", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("x-api-key", apiKey);
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
console.log("New record was added ...");
}
}
xhr.send(JSON.stringify(params));
};
window.onload = init;
Please, could you help with the delete function is not working as expected
Please, see attached file
Your code is sending an Object in the body
You're also setting the values of the properties to the literal strings 'studentId' and 'taskDescription'
The following may fix your issue
body: JSON.stringify({
'StudentId': studentId,
'Description': taskDescription,
'version': 'JSON',
})
I explain my problem to you, I have a table which contains several objects
under this form
{id:1,title:"Campus (Pinte)", desc:"Pression - Bière Blonde - 4° Alc", detail:"Une bière blonde légère qui saura vous désaltérer comme il se doit", qty:"50 cl", img:Campus, price: 5, ctg:1, },
I am currently posting my entire table like this
postbackend = () =>{
const config = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({...this.state, items:this.props.items}),
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
if (res.error) {
alert(res.error);
} else {
alert(`ajouté avec l'ID ${res}!`);
}
}).catch(e => {
console.error(e);
}).finally(()=>this.setState({ redirect: true }));
}
I want to post only whatever objects do not total it from my table
for example i only want to recover title qty and price
you have an idea of how to do . ? thx Neff
As this.props.items is an array, you need to map over the array to create a new array with objects that have only the desired fields.
const newItems = this.props.items.map((item) => {
const { title, qty, price } = item;
return {
title,
qty,
price
};
});
Then use the variables however you like:
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({...this.state, items: newItems }),
};
postbackend = () =>{
const { title, qty, price } = this.props.items;
const config = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({...this.state, items: { title, qty, price } }),
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
if (res.error) {
alert(res.error);
} else {
alert(`film ajouté avec l'ID ${res}!`);
}
}).catch(e => {
console.error(e);
}).finally(()=>this.setState({ redirect: true }));
}
when user wants to to POST somthing he must be singed in(without username & pass).
Problem is i'm trying to make when CreatePost() invoked it will call SingUser() and based on SingUser() fetch request it will call CreatePost() again to let user post after he sign in.
this is in createpost component
CreatePost(){
fetch(url ,{
method :'POST',
headers:{
Accept:'application/json',
'Content-Type' :'application/json',
},
body: JSON.stringify(post)
}).then((response) => response.json())
.then((responseJson)=>{
if(responseJson.status =='inactive'){
//SignUser
}else{
//post
}
}).catch((error)=>{ //later
});
}
here is SingUser() in other file
async function SignUser() {
try{
User.vtoken = await AsyncStorage.getItem('vtoken');
var userTemp={
vtoken: User.vtoken,
ntoken : User.ntoken
}
fetch(url,{
method :'POST',
headers:{
Accep : 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(userTemp)
}).then((response)=> response.json()).
then((responseJson)=>{
if(responseJson.path == 2){
Save(responseJson, userTemp);}
else return;
}).catch((error)=>{
});
}catch(error){}
}
async function Save(result , userTemp){
try{
await AsyncStorage.setItem('vtoken', result.vtoken);
User.vtoken = result.vtoken;
userTemp.vtoken = result.vtoken;
fetch(url,{
method :'POST',
headers:{
Accep : 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(userTemp)
}).then((response)=>response.json()).
then((responseJson)=>{
return 'done';
}).catch((error)=>{})
}
catch(error){}
}
export {SignUser}
i hope u understand what im trying to do if there is better way to do it thnx:(
You can do something like this:
const errorCodeMap = {
USER_INACTIVE: 10,
}
const statusMap = {
INACTIVE: `inactive`
}
const METHOD = `POST`
const APPLICATION_JSON = `application/json`
const headerDefault = {
Accept: APPLICATION_JSON,
'Content-Type': APPLICATION_JSON,
}
const who = `post`
async function createPost(payload, options) {
try {
const {
url = ``,
fetchOptions = {
method: METHOD,
headers: headerDefault,
},
} = options
const {
post,
} = payload
const response = await fetch(url, {
...fetchOptions,
body: JSON.stringify(post)
})
const {
status,
someUsefulData,
} = await response.json()
if (status === statusMap.INACTIVE) {
return {
data: null,
errors: [{
type: who,
code: errorCodeMap.USER_INACTIVE,
message: `User inactive`
}]
}
} else {
const data = someNormalizeFunction(someUsefulData)
return {
data,
errors: [],
}
}
} catch (err) {
}
}
async function createPostRepeatOnInactive(payload, options) {
try {
const {
repeat = 1,
} = options
let index = repeat
while (index--) {
const { data, errors } = createPost(payload, options)
if (errors.length) {
await signUser()
} else {
return {
data,
errors,
}
}
}
} catch (err) {
}
}
solve it, I did little adjustments
async CreatePost(){
try{
var response = await fetch(url ,{
method :'POST',
headers:{
Accept:'application/json',
'Content-Type' :'application/json',
},
body: JSON.stringify(post)});
var responseJson = await response.json();
if(responseJson.status =='inactive' && postRepeat == true){
postRepeat == false;
await SignUser();
this.CreatePost();
}
else{
//posted
}
}catch(err){}
}
I have a JavaScript loop iterating over an array. For every item, I perform a fetch request to insert the object. If the server response indicates it is an already inserted object, I try an update operation with another fetch call.
As the requests are asynchronous, the loop sets the request object to the next insert item before I try the update operation, so I end up requesting an update for an object it's not yet inserted.
Is there any way I can access the request object used for this fetch operation, so I can use that object instead of the loop var?
I've tried with this within the promise method, but it returns a reference to the window object: console.log(this) ==> > Window http://localhost
My code:
for (var i = 0; i < expectedRows; i++) {
var row = myArray[i];
customerCode = row['customer_code'];
customerName = row['customer_name'];
customerBalance = row['customer_balance'];
// Build body call
var callBody = {
user: 'USER',
code: customerCode,
name: customerName,
balance: customerBalance
};
var fetchOptions = {
method: "POST",
cache: "no-cache",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
redirect: "error",
referrer: "ux-import",
body: JSON.stringify(callBody),
};
// Call
var epurl = baseEP + '/customer/create';
fetch(epurl, fetchOptions)
.then(response => response.json())
.then(response => {
console.log(this) // <== Window object reference
if (response.error === 0) {
console.log('insert ok');
insertRows++;
} else {
if (response.error == 2) {
console.log('insert error => update');
var updateEP = baseEP + '/customer/update';
fetch(updateEP, fetchOptions) // <== Not what you expect
.then(updResponse => updResponse.json())
.then(updResponse => {
if (updResponse.error === 0) {
console.log('update ok.')
updateRows++;
} else {
console.log('update error: ' + updResponse.msg)
errorMessages.push(updResponse.msg);
}
})
.catch(error => {
console.log('update failure');
errorMessages.push(error);
});
} else {
console.log('insert error.');
errorMessages.push(response.msg);
}
}
})
.catch(error => {
console.log('insert failure.');
errorMessages.push(error);
});
}
I need some way to access this fetch call request object to achieve something like this:
var updFetchOptions = {
method: "POST",
cache: "no-cache",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
redirect: "error",
referrer: "ux-import",
body: this.request.body, // this as a reference to this fetch's request
}
fetch(updateEP, updFetchOptions)...
:
:
Can you try this.
for (let i = 0; i < expectedRows; i++) {
let row = myArray[i];
customerCode = row['customer_code'];
customerName = row['customer_name'];
customerBalance = row['customer_balance'];
// Build body call
let callBody = {
user: 'USER',
code: customerCode,
name: customerName,
balance: customerBalance
};
let fetchOptions = {
method: "POST",
cache: "no-cache",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
redirect: "error",
referrer: "ux-import",
body: JSON.stringify(callBody),
};
// Call
let epurl = baseEP + '/customer/create';
fetch(epurl, fetchOptions)
.then(response => response.json())
.then(response => {
console.log(this) // <== Window object reference
if (response.error === 0) {
console.log('insert ok');
insertRows++;
} else {
if (response.error == 2) {
console.log('insert error => update');
let updateEP = baseEP + '/customer/update';
fetch(updateEP, fetchOptions) // <== Not what you expect
.then(updResponse => updResponse.json())
.then(updResponse => {
if (updResponse.error === 0) {
console.log('update ok.')
updateRows++;
} else {
console.log('update error: ' + updResponse.msg)
errorMessages.push(updResponse.msg);
}
})
.catch(error => {
console.log('update failure');
errorMessages.push(error);
});
} else {
console.log('insert error.');
errorMessages.push(response.msg);
}
}
})
.catch(error => {
console.log('insert failure.');
errorMessages.push(error);
});
}
Basically, defining variables with var is not a good method as it doesn't maintain its state with each iteration of loop. But using let maintains the variable state for each iteration and you can use the variable even after doing some async task like fetch in your case.
You can achieve this by explicitly creating the RequestInit-Object and wrapping your handler functions like this:
const initObject = {
method: 'POST',
something: 1234
};
fetch('/test.json', initObject)
.then(r => r.json())
.then(((initObject) => {
return json => {
console.log({json, initObject})
}
})(initObject));
I have a conditional fetch that determines a part of a URL for a subsequent fetch, but I only want it to run in certain conditions.
The following is not waiting and runs the try right away:
async function fetchURLs() {
let sessionWait = false;
if ((check1 === true) && (check2 === false))
{sessionWait = await getURL();
} else {sessionWait = true}
if (sessionWait === true){
try {
var [a, b, c] = await Promise.all([
fetch(dataUrl, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'post',
}).then((response) => response.text()).catch(error => console.log(error.message)),
fetch(settingsUrl).then((response) => response.text()).catch(error => console.log(error.message))
} catch (error) {
console.log(error);
}
});
}
async function getURL(){
let subDomain = 'a';
fetchAdd = "https://" + subDomain + ".dexcom.com/ShareWebServices/Services/General/LoginPublisherAccountByName"
await fetch(fetchAdd, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
}).then((res) => res.json()).then((SessionData) => dataUrl = "https://" + SessionData).catch(error => console.log(error.message));
return true;
}
const tasks = getTaskArray();
return tasks.reduce((promiseChain, currentTask) => {
return promiseChain.then(chainResults =>
currentTask.then(currentResult =>
[ ...chainResults, currentResult ] )
);
}, Promise.resolve([])).then(arrayOfResults => {
// Do something with all results
});
This Link might help you.
https://decembersoft.com/posts/promises-in-serial-with-
array-reduce/