I have already started question about this on AngularJS, factory, do POST then GET method. I have to do POST request get json like {'exp':'2+3','token':'asd'}(SoluableNonagon answerd me very well), then get the token from json and to GET request like /something/:token, before that I'll have to check if token exist in json that i got with POST method. Can anyone tell me how can I do this and how can I call factory from controller that is doing post request?
every $http functions returns a promise, promises can be nested or serialized the return inside the function must be a promise in order to serialize your operations, the next then will be called when the $http.get is finally finished.
$http.post('post1').then(function (resultPost1) {
// do your stuff
return $http.get('get1');
}).then(function (resultGet1) {
// do your stuff
return $http.get('get2').then(function (resultGet2) {
// do your nested stuff
return $http.get('get3');
});
}).then(function (resultGet3) {
// do your stuff
});
More info on $q docs: https://github.com/kriskowal/q
Related
I'm using VueJS 2.0 with SuperAgent in order to create an API client connector. I'm working on test coverage for my API and having trouble when it comes to test SuperAgent methods itself. I need to know how to spy on my private methods within superagent requests:
This is what my SuperAgent request looks so far:
// Importing superagent as request
import request from 'superagent';
if (['get', 'head'].includes(method)) {
return request[method](this.Url(path, opts))
.set(getHeader())
.query(params)
.then(handleSuccess, handleError);
}
return request[method](this.Url(path, opts))
.set(getHeader())
.query(params)
.then(handleSuccess, handleError);
This is inside a conditional because, otherwise, if the HTTP method is not GET or HEAD, the query(params) won't be passed (since it's not needed in this case).
Question 1: How can I spy on superagent in order to know if my promise returned a successful response? Even though I'm not using superagent's promise (since I'm using then() instead of end()), I still need to spy on superagent request;
Question 2: How can check if the query() method has been called by superagent instance (request)?
Test case 1 (using Jasmine):
it('should set the query params if the method IS "get" or "head"');
Test case 2:
it('should call the success callback if the response code is between 200 and 299');
Any thoughts?
I am trying to return an array of data inside a JSON object that is return from a URL, I can see the data that is being returned using console.log.
However when trying to catch the return array in a variable for example:
var arr = list();
console.log(arr.length);
The length being output by this code is "0" despite the fact that the data returned has content (so the length is greater than zero). How can I use the data?
list: function() {
var grades = [];
$.getJSON(
"https://api.mongolab.com/api/1/databases", function(data) {
console.log(data);
grades [0] = data[0].name;
console.log(grades.length);
});
return grades;
},
The issue you are facing is easy to get snagged on if you aren't used to the concept of asynchronous calls! Never fear, you'll get there.
What's happening is that when you call the AJAX, your code continues to process even though the request has not completed. This is because AJAX requests could take a long time (usually a few seconds) and if the browser had to sit and wait, the user would be staring in angsuish at a frozen screen.
So how do you use the result of your AJAX call?
Take a closer look at the getJSON documentation and you will see a few hints. Asynchronous functions like getJSON can be handled in two ways: Promises or Callbacks. They serve a very similar purpose because they are just two different ways to let you specify what to do once your AJAX is finished.
Callbacks let you pass in a function to getJSON. Your function will get called once the AJAX is finished. You're actually already using a callback in the example code you wrote, it's just that your callback is being defined inside of your list() method so it isn't very useful.
Promises let you pass in a function to the Promise returned by getJSON, which will get called once the AJAX is finished.
Since you are doing all this inside of a method, you have to decide which one you're going to support. You can either have your method take in callbacks (and pass them along) or you can have your method return the promise returned by getJSON. I suggest you do both!
Check it out:
var list = function(success) {
// Pass in the callback that was passed into this function. getJSON will call it when the data arrives.
var promise = $.getJSON("https://api.mongolab.com/api/1/databases", success)
// by returning the promise that getJSON provides, we allow the caller to specify the promise handlers
return promise;
}
// Using callbacks
list(function(grades) {
console.log(grades);
});
// Using promises
list()
.success(function(grades) {
console.log(grades);
});
I have the following situation:
I use ngResource to save some data to the mysql database and after the successfull save() I want to log the json response the server sends to me:
Document.save({}, postData, function(response){
console.log(response);
});
This does not result in a simple response, but in something like an object with its own methods. I want some smple output like the response.data after an $http.$get:
{
"docClass":"testets",
"colCount":1,
"columns":null,
"groupid":7,
"id":19,
"lang":"de",
"title":"test",
"version":1409849088,
"workflow":"12234"
}
Greets
Check out this answer
Promise on AngularJS resource save action
So I think in your case you need to do
var document = new Document(postData);
document.$save()
.then(function(res){});
But also from the link I provided
This may very well means that your call to $save would return empty reference. Also then is not available on Resource api before Angular 1.2 as resources are not promise based.
I'm learning d3js. I came across an example for extracting CSV values here. I'm quoting the code:
d3.csv("path/to/file.csv")
.row(function(d) { return {key: d.key, value: +d.value}; })
.get(function(error, rows) { console.log(rows); });
From the description, I get that .row() is the accessor here. But the role of the .get() is not clear to me. When is this function called, and for what purpose ? Thanks.
The .get() is a function of the underlying AJAX request -- it sends the request and establishes the callback. From the documentation:
xhr.get([callback])
Issues this request using the GET method. If a callback is specified, it will be invoked asynchronously when the request is done or errors; the callback is invoked with two arguments: the error, if any, and the response value.
I’m using jQuery to make an AJAX call to Node.js to get some JSON. The JSON is actually “built” in a Python child_process called by Node. I see that the JSON is being passed back to the browser, but I can’t seem to parse it—-although I can parse JSONP from YQL queries.
The web page making the call is on the same server as Node, so I don’t believe I need JSONP in this case.
Here is the code:
index.html (snippet)
function getData() {
$.ajax({
url: 'http://127.0.0.1:3000',
dataType: 'json',
success: function(data) {
$("#results").html(data);
alert(data.engineURL); // alerts: undefined
}
});
}
server.js
function run(callBack) {
var spawn = require('child_process').spawn,
child = spawn('python',['test.py']);
var resp = '';
child.stdout.on('data', function(data) {
resp = data.toString();
});
child.on('close', function() {
callBack(resp);
});
}
http.createServer(function(request, response) {
run(function(data) {
response.writeHead(200, {
'Content-Type':
'application/json',
'Access-Control-Allow-Origin' : '*' });
response.write(JSON.stringify(data));
response.end();
});
}).listen(PORT, HOST);
test.py
import json
print json.dumps({'engineName' : 'Google', 'engineURL' : 'http://www.google.com'})
After the AJAX call comes back, I execute the following:
$("#results").html(data);
and it prints the following on the web page:
{“engineURL": "http://www.google.com", "engineName": "Google"}
However, when I try and parse the JSON as follows:
alert(data.engineURL);
I get undefined. I’m almost thinking that I’m not actually passing a JSON Object back, but I’m not sure.
Could anyone advise if I’m doing something wrong building the JSON in Python, passing the JSON back from Node, or simply not parsing the JSON correctly on the web page?
Thanks.
I’m almost thinking that I’m not actually passing a JSON Object back, but I’m not sure.
Yes, the ajax response is a string. To get an object, you have to parse that JSON string into an object. There are two ways to do that:
data = $.parseJSON(data);
Or, the recommended approach, specify dataType: 'json' in your $.ajax call. This way jQuery will implicitly call $.parseJSON on the response before passing it to the callback. Also, if you're using $.get, you can replace it with $.getJSON.
Also:
child.stdout.on('data', function(data) {
resp = data.toString();
// ^ should be +=
});
The data event's callback receives chunks of data, you should concatenate it with what you've already received. You probably haven't had problems with that yet because your JSON is small and comes in a single chunk most of the time, but do not rely on it, do the proper concatenation to be sure that your data contains all the chunks and not just the last one.