Return full data on JavaScript Promise for a function within a class while using node-client-ntlm - javascript

I have a function within a class that makes a call and returns a promise object with data. I do get the data back the issue is I cannot figure out how to make the call wait till all of the data is returned at the moment it only returns a few lines of data and cuts off the rest of the return.
async callCurl(postFields) {
this.postFields = postFields;
const response = await client
.request(
{
url: this.url,
method: "POST",
debug: true,
body: "folderGuid=" + this.postFields,
headers: {
"content-type": "application/x-www-form-urlencoded",
},
resolve: true,
},
"username",
"password",
"",
"domain"
)
.then((response) => {
console.log(response.body);
})
.catch(function (error) {
console.log(error);
});
//return response;
}

Related

How to call API Ninjas API with Javascript?

I am trying to use an API from https://api-ninjas.com/api/geocoding/. Their site provides the following starter code for how to call an API, but when I try it, the browser console just tells me that $ is not defined.
Is $.ajax a stand-in for something I need to create?
Here is the starter code they provide:
var city = 'london'
$.ajax({
method: 'GET',
url: 'https://api.api-ninjas.com/v1/geocoding?city=' + city,
headers: { 'X-Api-Key': 'YOUR_API_KEY'},
contentType: 'application/json',
success: function(result) {
console.log(result);
},
error: function ajaxError(jqXHR) {
console.error('Error: ', jqXHR.responseText);
}
});
I have tried writing document.ajax, but that returned the error that it was not a function. I have also tried deleting $.ajax and putting fetch in its place
I was able to solve with the following code:
let options = {
method: 'GET',
headers: { 'x-api-key': 'myKey' }
}
let url = 'https://api.api-ninjas.com/v1/geocoding?city=denver'
fetch(url,options)
.then(res => res.json()) // parse response as JSON
.then(data => {
console.log(data)
})
.catch(err => {
console.log(`error ${err}`)
});

Problem with a 'double fetch' call in React Native

I am having problems using 'nested' Fetch calls within a React Native function. It seems the first Fetch works correctly, however an error is thrown on the second. Here is the code:
//****CALL TWO FETCH REQUESTS...
const data = { passkey: '12345', callup: 'name' };
const secondary = { passkey: '12345', callup: 'name' };
fetch('https://myremoteserveraddress', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(function(response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
})
.then(data => {
// Store the post data to a variable
_post = data;
console.log('Success on FIRST FETCH:', data);
console.log('answer is:', data.answer);
console.log('answer is:', _post.answer);
// Fetch another API
fetch('https://myremoteserveraddress', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(secondary),
})
})
.then(function (response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
})
.then(function (userData) {
console.log('Returned from BOTH fetch calls'); //does not write to console
console.log(_post, userData); //does not write to console
this.vb.start();
})
.catch((error) => {
console.error('Error in onPressPublishBtn:', error);
});
//****
It seems the second Fetch call returns 'undefined', despite being identical to the first Fetch call which seems to work successfully. The error returned is "TypeError: undefined is not an object (evaluating 'response.ok')". If anybody can advise on what the problem may be I would be greatly appreciative. Thank you in advance.
You should return a Promise from the second then(...) block so that the response is passed to the third then(...) block. You might want to try something like this:
// Fetch another API
return fetch('https://myremoteserveraddress', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(secondary),
})

Performing POST method Using Axios and Pipe Function

So I am currently learning about FP and the use of the Pipe operator which combines n functions and simply calls it from left to right. Currently, I am trying to make a POST call using Axios and then handle the data returned appropriately, but then the pending promise value always results to undefined. Here is what my code looks like.
The pipe function
const pipe = (...fns) => (initValue) => fns.reduce((v, f) => f(v), initValue)
Here is the first function that is passed to the pipe function
const dataToPost = ({ title, body, userId }) => {
return {
method: 'post',
url: 'https://jsonplaceholder.typicode.com/posts',
data: {
title,
body,
userId,
},
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
}
}
Here is how I implement the pipe function passing it the various arguments
const postTodoFunc = ({ pipe }) => {
return async function postTodo({ title, body, userId }) {
const callJSONAPI = pipe(dataToPost, axios, output) ///this line here
const calledFunc = await callJSONAPI({
title,
body,
userId,
})
return calledFunc
}
}
The output function looks like this.
const output = (response) => {
return response.data
}
The postTodoFunc is invoked like this
const postedTodo = postTodoFunc({ pipe })
const result = postedTodo({
title: 'Rule the world',
body: 'some random body',
userId: 1,
})
console.log(result) // undefined
Now from my understanding, the dataToPost function is called first which returns an object that is equivalent to this
{
method: 'post',
url: 'https://jsonplaceholder.typicode.com/posts',
data: {
title,
body,
userId,
},
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
}
This object is then passed to axios which is then equivalent to the following format
axios({
method: 'post',
url: 'https://jsonplaceholder.typicode.com/posts',
data: {
title,
body,
userId,
},
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
The response from this axios call returns undefined. Because I thought the response will be passed to the next function which is this case output function. But that does not seem to be the case. How can I fix this and get the correct data? Initially from the JSONPlaceholder website, the response is meant to be like this
{
id: 101,
title: 'Rule the world',
body: 'Some random body',
userId: 1
}
but then again, I am getting undefined after the pending promise.

nodejs promise best way to implement from settimeout

I have the following functions working in nodejs, but I am using a setTimeout rather than a promise. If the createchange takes longer than the timeout I have, my code fails but does not catch the error correctly.
How would I substitute or change the following function(s) to work with a promise, so deploychange waits for createchange to complete, before continuing through the code?
I've tried a couple things but nothing seems to work. Not sure which function I should redo either for the most effective solution.
Any help would be appreciated.
First function
function createchange(accessToken){
const data = {
templateName: "Template 1",
summary: "Deploy Change",
configurationItems: [
config_item
],
wasEnvUsedForTesting: false,
environment: test_env
};
rp({
url: dbConfig.cmas_url,
resolveWithFullResponse: true,
method: 'POST',
json: true,
auth: {
bearer: accessToken
},
body: data,
headers: {
'Content-Type': 'application/json',
'apikey': dbConfig.consumer_key,
},
}, function(err, res) {
if(err){
console.log(err.body);
}else{
console.log(res.body);
crq = res.body.changeid;
}
});
}
2nd function
function run() {
deploychange();
setTimeout(function(){ deployinsert(); }, 7500);
deployrun();
}
3rd function
function deploychange (callback) {
if (req.body.deployEnv == "PRD"){
getToken(function(accessToken) {
createchange(accessToken);
})};
}
According to the request-promise documentation, rp returns a promise.
You can actually convert your createChange function to return a promise like so:
const createchange = accessToken => {
const data = {
templateName: 'Template 1',
summary: 'Deploy Change',
configurationItems: [config_item],
wasEnvUsedForTesting: false,
environment: test_env
};
return rp({
url: dbConfig.cmas_url,
resolveWithFullResponse: true,
method: 'POST',
json: true,
auth: {
bearer: accessToken
},
body: data,
headers: {
'Content-Type': 'application/json',
apikey: dbConfig.consumer_key
}
});
};
You can then call your function with the await keyword.
await createchange(accessToken);
Make sure that the function using await is marked with async
You can also write it like this:
createchange(accessToken)
.then(({changeId}) => {
// Do someth with the changeId
})
.catch(/* Error handling */)

Make another ajax call to get headers before each actual ajax call - jquery

I have to make an async call which uses cookie to get bearer token which has to be passed to make actual ajax call for the resource.
And I have written the following code which works awesome and get's me the result.
Can I use ajaxPrefilter or beforeSend options to get the tokens, I tried to find documentation for ajaxPrefilter which says it accepts a function, but does that waits for that function to be finished before making actual call?
Token retrieval function
function getTokenUsingCookieAsync() {
return new Promise(function (resolve, reject) {
$.ajax('/retrieve-token').done(function (result) {
resolve(result.token);
}).fail(function (message) {
reject(message);
});
});
}
Actual execute function:
function execute(url, method, data) {
var deferred = $.Deferred();
getTokenUsingCookieAsync().then(function (response) {
var reqSettings = {
async: true,
url: url,
cache: false,
type: method,
headers: {
Authorization: 'Bearer '+ response,
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: data ? JSON.stringify(data) : null
};
$.ajax(reqSettings).done(function (result) {
deferred.resolve(result);
}).fail(function (message) {
deferred.reject(message);
});
}).catch(function (message) {
deferred.reject(message);
});
return deferred.promise();
}
So the following pseudo code is possible or not?
$.ajaxPrefilter((options) => {
$.ajax('/retrieve-token').done((result) => {
options.headers = {
Authorization: `Bearer ${result}`
};
});
});
$.ajax('actual-url')
.done(whatever);

Categories

Resources