i've been reading a lot from stack overflow and a book called"You Don't Know Javascipt" (which is a fantastic book series btw by kyle simpson) but im still struggling with asynchronous ajax scripting. Does anyome have any reaources for asynch js coding and promises? Im trying to pull jsons from apis and parse the data to assemble the next url for the next api call and do it in order (as one does) and im having a lot of difficulty. This kind of stuff is so central to the web i want to just make sure im not shooting myself in the foot when i code these calls. Any and all help and recommendations would be greatly appreciated thanks!
I use POSTMAN to check my API before testing any code in Angular JS, just to make sure I am getting what I expect in response.
HTH
A simple native Javascript solution for your use case would be
fetch('url1').then(res1 => {
const {urlParam} = res.url; // if url is an object
const url2= `construct_your_url_here_${urlParam}`;
return url2
}).then(newUrl => {
fetch(newUrl).then()
})
In more concise ES6 way
fetch('/article/promise-chaining/user.json')
.then(response => response.json())
.then(user => fetch(`https://api.github.com/users/${user.name}`))
.then(response => response.json())
.then(githubUser => {
let img = document.createElement('img');
img.src = githubUser.avatar_url;
img.className = "promise-avatar-example";
document.body.append(img);
setTimeout(() => img.remove(), 3000);
});
More reading - javascript.info/promise-chaining
Hey, I don't know if this is still the newest way to do it, but putting everything in an async series function is a good way to do this.
Here's a working example - github.com/spsiddarthan/comment-syncer-api/blob/m…
Peter Scheler
JS enthusiast
Try the fetch API.
Also the async/await feature of JS (ES2017) will be a great help. (Please compare here)
PS: Please notice, the latest features will only be available in the latest browser versions (see here). If you want to support older browsers you need to transpile and/or polyfill you code.