I want to post files to groups. by storing the group id I want to send files to groupsFinal, but axios.post() will only post to the first array of groupsFinal, I tried for loop but it fails axios post.
let groups = [{id:"a001", groupName:"Group101"},{id:"a002", groupName:"Group202"}]
let groupsFinal = [];
for (let a = 0; a < groups.length; a++) {
let d = JSON.parse(JSON.stringify(groups[a]));
d.img = null;
groupsFinal.push(d);
}
let p = {
fileId: "file_001",
groups: groupsFinal, // array[]
};
return new Promise((resolve, reject) => {
axios
.post("/shareFileToGroup", p, {
headers: {
"Content-Type": "application/json"
},
})
.then(function (response) {
resolve("success");
})
.catch(function (error) {
reject("error");
})
.finally(function () {
// always executed
});
});
Related
Here is my code, I pass array of ids and for each ids I hit Api request.
for (let i = 0; i < 10; i++) {
cy.request({
method: 'GET',
url: `https://[API endpoint ]/api/v1/[requst]/${ids[i]}`,
headers: {
"authorization": token
}
})
.then((res) => {
return usernames.push([{ value: res.body.instagrams[0].username }])
})
.then((res) => {
return cy.wait(2000)
})
}
Whenever I execute the code, for 2-3 requests it works fine and then throws error like
Uncaught Error: invalid payload
I can see my URI is proper and sending correct request.
you should modify your code to wrap all the pending promises into an array. A modified snippet is as below:
async function processRequest(){
let result;
let promises = [];
for (let i = 0; i < 10; i++) {
promises.push(cy.request({
method: 'GET',
url: `https://[API endpoint ]/api/v1/[requst]/${ids[i]}`,
headers: {
"authorization": token
}
}))
}
result = await Promise.all(promises);
for(let i = 0; i < 10; i++){
usernames.push([{ value: result[i].username }])
}
}
Here cy.request doesn't work properly with Promise.
Either while pushing it to promise array, remove cy.request() or purely handle with javascript.
async findUserName(ids, token) {
let promise = []
let usernames = []
ids.forEach(id => {
promise.push(
fetch(`https://[host]/api/v1/[endpoint]/${id}`, {
headers: {
'Content-Type': 'application/json',
"authorization": token
}
})
.then((res) => {
return res.json();
})
)
})
let result = await Promise.all(promise);
result.forEach((data) => {
usernames.push([{ value: data.instagrams[0].username }])
})
return usernames
}
I'm trying to call an API inside a for loop using Nodejs,when the code is executed only the last element is called by the API:
the code :
var array=[12,124,852,256,5677,256,5679,2546,567,28,574]
for(var i=0;i<array.length;i=i++){
var b = array.splice(i,3);
const parameters1 = {
Ids: b.toString(),
limit: 45,
}
const get_request_args1 = querystring.stringify(parameters1);
const options1 = {
method: 'GET',
host: "host",
port: '443',
path: path + '?' + get_request_args1,
headers: {
'Accept': 'application/json',
'authorization': `Bearer ${token}`,
'Accept-Encoding': 'identity',
}
}
var req = http.request(options1, (res) => {
context.log("API CALL...",i);
var body = "";
var pages = 0;
var offset = [];
var limit = 100000;
res.on("data", (chunk) => {
body += chunk;
});
res.on("end", () => {
const obj = JSON.parse(body);
//context.log('total pages 3 :', pages);
context.log('total :', obj.total);
context.res = { body: offset };
context.done();
});
}).on("error", (error) => {
context.log('ERROR :', error);
context.res = {
status: 500,
body: error
};
context.done();
});
}
when this code is executed only the last element in the array executed by the API, what I'm looking for is executing the api for each iteration of the for loop, any helps please ?
Not sure how your full function looks like, but you should build your function as fully structured as async-await.
And also you could use map function instead of for.
const yourFunction = async () => {
try {
const array = [12,124,852,256,5677,256,5679,2546,567,28,574];
const requests = array.map(async (item) => {
...
var req = await http.request(async options1, (res) => {
context.log("API CALL...",i);
...
});
await Promise.all(requests);
...
} catch (err) {
console.error(err);
}
}
I can't understand what the problem is, the essence of this request is to pass some data, call a function and send back the generated Json file, but this does not happen, instead the server does not return anything. What could be the problem? Please help me
Web part
clickOnRow: function(elem, whichScreen){
this.clicks++
if(this.clicks === 1) {
var self = this
this.timer = setTimeout(function() {
console.log("одинарный");
self.clicks = 0
}, this.delay);
} else{
clearTimeout(this.timer);
console.log("двойной");
elem['whichScreen'] = whichScreen;
console.log(this.helper);
// this.nameOfMethod(elem);
this.clicks = 0;
fetch('/currentDir1',{
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(elem)
})
.then(response => response.json())
.then(json => this.helper = json)
.then(json => this.$emit("newvalue", json))
console.log("helper");
console.log(this.helper);
Server part
router.post('/currentDir1',(req, req) =>{
console.log("POST");
let body = "";
let pathToFile = "";
req.on("data", function (data) {
body += data;
});
req.on("end", function(currentData) {
console.log(JSON.parse(body));
currentData = JSON.parse(body);
if(currentData.sizeOrType === "<папка>"){
let dir = currentData.dir + currentData.fileName;
// dir = "C:\\totalcmd";
console.log(dir);
if(currentData.whichScreen){
foo(dir, './data/firstScreen.json');
pathToFile = './data/firstScreen.json';
res.sendFile(path.resolve('./data/firstScreen.json'));
}else{
console.log('aaaa');
Foo(dir, './data/secondScreen.json');
pathToFile = './data/firstScreen.json';
res.sendFile(path.resolve('./data/secondScreen.json'));
}
}
// res.json({ message: 'goodbye'})
res.json(path.resolve(pathToFile));
});
res.sendFile(path.resolve(pathToFile));
})
I am trying to Post a large JSON into my Database, the JSON has at least 400.000 Objects.
If I cut the file, and try to Post 20.000 Objects everything works just fine, so the problem should be JSON's size.
I've split the JSON into 20 chunks, and my idea is to upload one at a time but i'm struggling to make it work.
This is what I'm using:
var rows = {};
Papa.parse(content, {
header: false,
delimiter: '|',
worker: true,
encoding: "utf16le",
dynamicTyping: true,
skipEmptyLines: true,
complete: function(results) {
rows = results.data;
let obj = []
for(var i=0; i < rows.length; i++){
obj.push(rows[i])
}
let result = []
for(let i in obj) {
let temp = {}
if(i > 0) {
temp["id"] = obj[i][0]
temp["name"] = obj[i][1]
temp["tel"] = obj[i][2]
temp["email"] = obj[i][3]
temp["status"] = obj[i][5]
result.push(temp)
}
}
var array1 = result.map((e) => {
return {
id: e.id,
name: e.name,
email: e.email
}
})
let chunked = []
let size = 20000;
Array.from({length: Math.ceil(array1.length / size)}, (val, i) => {
chunked.push(array1.slice(i * size, i * size + size))
})
console.log(chunked); // at this point I have my array divided into chunks of 20000
axios({
url: 'url',
method: 'post',
data: chunked
})
.then(function (response) {
// your action after success
console.log(response);
})
.catch(function (error) {
// your action on error successif (error.response) {
console.log(error);
});
You can send it one by one as follow. Assuming your backend is able to accept the data format.
for(let i=0;i<chunked.length;i++){
axios({
url: 'url',
method: 'post',
data: chunked[i]
})
.then(function (response) {
// your action after success
console.log(response);
})
.catch(function (error) {
// your action on error successif (error.response) {
console.log(error);
});
}
Or a modern solution could be to use Promise.all([])
let promiseArray = [];
for(let i=0;i<chunked.length;i++){
promiseArray.push(axios({
url: 'url',
method: 'post',
data: chunked[i]
}))
}
Promise.all(promiseArray)
.then((responses) => {
console.log(responses); //Will return resolved/rejected promises in an array
})
.catch(error => {
console.error(error.response)
});;
You can read more about Promise.all([]) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
I am calling API to fetch data on the basis of that data I am calling different APIs which is based on condition.
I have used a promise to maintain the async code as well but no luck so far. At the end of the block, I want every data pushed inside array but I am getting a blank array.
async (body, nextCall) => {
var tmpArryOfModuleList = []
var bodyData = body.data
var promise = new Promise((resolve, reject) => {
bodyData.forEach(element => {
if (element.hasCRUD === '0') {
var options = {
method: 'GET',
url: `${apiURL}/api/fetchAllCharts`,
headers:
{
Authorization: token
}
};
request(options, function (error, response, dashboardData) {
if (error) {
return nextCall({
error: error
})
}
var parsedDashboardData = JSON.parse(dashboardData)
for (var i = 0; i < parsedDashboardData['data'].length; i++) {
var val = element.name + " - " + parsedDashboardData['data'][i]['name']
var randomID = Math.random().toString(36).slice(2)
tmpArryOfModuleList.push({ "_id": randomID, "submodule": val })
}
});
} else if (element.hasCRUD == '1') {
var options = {
method: 'GET',
url: `${apiURL}/api/fetchAllActions`,
headers:
{
Authorization: token
}
};
request(options, function (error, response, crudData) {
if (error) {
return nextCall({
error: error
})
}
var parsedcrudData = JSON.parse(crudData)
for (var i = 0; i < parsedcrudData['data'].length; i++) {
var val = element.name + " - " + parsedcrudData['data'][i]['name']
var randomID = Math.random().toString(36).slice(2)
tmpArryOfModuleList.push({ "_id": randomID, "submodule": val })
}
});
} else {
console.log('no data found')
reject('No Data Found')
}
})
resolve(tmpArryOfModuleList)
})
console.log('tmpArryOfModuleList', tmpArryOfModuleList)
}
What am I doing wrong? How can I achieve the result on the last array?