call function after multiple loops of fetch() - javascript

If i want to call doStuff()
when multiple loops of fetch are finnish, how would i approach it ?
im assuming i need to call a function every time a fetch is done and check if concat of both array length is at the last one ?
let array1 = [1,2]
let array2 = [7,8]
array1.map(function(item){
fetch("/api/execution/"+item, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
});
array2.map(function(item){
fetch("/api/something/"+item, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
});
//call doStuff only when all the fetchs are done
function doStuff(){
console.log("yay")
}

You're using .map() to launch the requests but you're not saving the returned Promise instances.
let p1 = array1.map(function(item){
return fetch("/api/execution/"+item, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
});
And similarly for array2. You can then concatenate the two arrays of Promises and use Promise.all():
let p1 = array1.map(function(item){
return fetch("/api/execution/"+item, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
});
let p2 = array2.map(function(item){
return fetch("/api/something/"+item, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
});
Promise.all(p1.concat(p2)).then(function(fetchedValues) {
// all fetch calls are finished
});

Related

send request using Fetch method

I need to send request using 'fetch' method. I need to send below data to my header
I need to send below data in request body
i am trying to do it using below code. but actually I have not proper idea to do it. can u help me.
fetch("http://disaida.com/api/endpoint/", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
PREPAY: ppy,
InputParameters: int
})
})
.then( (response) => {
});
Your data format is incorrect.
TRY
Also, based on your description, you might have to add the cookie property to your header
let data = {
PREPAY: {
InputParameters: {
P_USER_NAME : "SANJEEWA.LAKNATH1#HUAWEI.COM"
}
}
}
fetch("http://disaida.com/api/endpoint/", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then( (response) => {
console.log("RR"+response.json())
}).catch(err => console.log("error",err));

Nodejs create diffrent post request

I’ve the following code which works when using standalone request (not promise all) , but I don’t know how can I send two request with different form data properties (see aaaa/bbbb exmaple)
e.g. this is what I need to pass for the first request (different scope)
formData.append('grant_type', 'client_credentials');
formData.append('scope', ‘aaaa’);
And this is to the second request (in the promise all)
formData.append('grant_type', 'client_credentials');
formData.append('scope', ‘bbbbb');
This is the code:
let [res1,res2] = await Promise.all([axios({
method: 'post',
url: 'https://oauth2.md/oauth2/token',
headers: {
'Authorization': 'Basic [userpassword]',
...formData.getHeaders()
},
data: formData
},
{
method: 'post',
url: 'https://oauth2.md/oauth2/token',
headers: {
'Authorization': 'Basic [userpassword]’,
...formData.getHeaders()
},
data: formData
}
)])
console.log(res1.data.access_token)
Could I append it inline for each request? I try to put an object with those properties and it doesn't compile
is there a way to do something like this
{
method: 'post',
url: 'https://oauth2.md/oauth2/token',
headers: {
'Authorization': 'Basic [userpassword]’,
...formData.getHeaders()
},
data: formData.append([{
'grant_type': 'client_credentials'
},{
'scope': 'aaaa`
}])
}
update:
I've tried to do something like
let [res1, res2] = await Promise.all([
axios({
method: 'post',
url: 'https://oauth2.md/oauth2/token',
headers: {
'Authorization': 'Basic [userpassword]',
...formA.getHeaders()
},
data: formA
}),
axios({
method: 'post',
url: 'https://oauth2.md/oauth2/token',
headers: {
'Authorization': 'Basic [userpassword]',
...formB.getHeaders()
},
data: formB
})
])
console.log(res1.data.access_token)
function formA() {
formData.append('grant_type', 'client_credentials');
formData.append('scope', 'aaaa');
return formData
}
function formB() {
let formData = new FormData();
formData.append('grant_type', 'client_credentials');
formData.append('scope', 'bbbb');
return formData
}
Which doesn't work, now if I create the object inside like it works but the code is ugly, is there a better way to achieve this
function formB() {
let formData = new FormData();
formData.append('grant_type', 'client_credentials');
formData.append('scope', 'bbbb');
return formData
}
You're nearly there.
The main problem is that the axios function needs to be called multiple times in the Promise.all function.
With the above solved, my last recommendation is to make separate form-data objects for each request.
For example:
var formData1 = getFormDataObjectSomehow()
var formData2 = getAnotherFormDataObjectSomehow()
let [res1, res2] = await Promise.all([
axios({
method: 'post',
url: 'https://oauth2.md/oauth2/token',
headers: {
'Authorization': 'Basic [userpassword]',
...formData1.getHeaders()
},
data: formData1
}),
axios({
method: 'post',
url: 'https://oauth2.md/oauth2/token',
headers: {
'Authorization': 'Basic [userpassword]',
...formData2.getHeaders()
},
data: formData2
})
])
console.log(res1.data.access_token)
EDIT:
And don't forget to handle errors thrown from the axios requests. Either add .catch() block to your Promise.all or use a try/catch guard.

fetch. Processing 500 responses from the server

I send this request to the server:
fetch('/changeCountProductInCart', {
method: 'POST',
body: JSON.stringify({
product_id: this.dataset.product_id,
action: 'changeByInput',
nodeName: this.nodeName,
product_count: this.value
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).then(res => {
if(res.ok) {
totalAmount();
} else if(!res.ok) {
return res.json();
}
}).then(body => {
this.value = body.stock;
});
I want to go to then only if the response from the server only is not in the range of 200-300,but I just started to delve into promise and can't find the answer to my question
P.S. I will be grateful for any help or hint
You need to catch the server error responses:
fetch('/changeCountProductInCart', {
method: 'POST',
body: JSON.stringify({
product_id: this.dataset.product_id,
action: 'changeByInput',
nodeName: this.nodeName,
product_count: this.value
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.catch(err => /* error getting server response*/);

Fetch call freezes

I am using fetch to read data from a API:
async _getDcnDetail(dcnId) {
return await fetch(API_URL+'get_dcndetail', {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization':'Bearer '+ this.state.accessToken
},
body: JSON.stringify({
DcnId: dcnId
})
}).then(response => response.json());
}
Then I call it:
async componentDidMount() {
let response = await this._getDcnDetail(dcn.DcnId);
console.log(response);
}
But it "waits" eternally, it is not resolving the promise.
As I understand fetch returns a promise which gets resolved by response.json(). I use "await" to wait the promise to be resolved, so not sure, what is wrong.
First of all check if some error occured on your POST request
async _getDcnDetail(dcnId) {
return await fetch(API_URL+'get_dcndetail', {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization':'Bearer '+ this.state.accessToken
},
body: JSON.stringify({
DcnId: dcnId
})
}).then(response => response.json())
.catch(err => alert("maybe some error occured"));
}
Additionally, you should refactor this as,
async _getDcnDetail(dcnId) {
try{
const response = await fetch(API_URL+'get_dcndetail', {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization':'Bearer '+ this.state.accessToken
},
body: JSON.stringify({
DcnId: dcnId
})
});
response = response.json();
return response;
} catch(e){
console.log("error", e);
throw err;
}
}
Do have a look on promises and async/await

fetch API POST request response

I am trying to get output from the post request once the form has been submitted but I get a promise response rather than the actual data when posting the form
fetch('localhost/clients', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(formData)
}).then(response => {
console.info('Sending Message ...')
console.info(response.json())
}).catch (error => {
console.log(error)
})
The data gets passed to the backend however I want to return the data thats been outputted by the API server.
response.json() returns a Promise. You need to use it like below.
fetch('localhost/clients', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(formData)
}).then(response => {
return response.json();
}).then(jsonResponse => {
console.log(jsonResponse);
}).catch (error => {
console.log(error)
})

Categories

Resources