I have an function using axios where I am deleting multiple records based on the number of ids returned for a specific user.
async function DeleteAllRecords (emailAddress) {
try {
var accessToken = await setup.getAccessToken(emailAddress);
var userId = await user.getUserId(emailAddress);
var recordIds = await getAllRecordID(emailAddress);
console.log(`Deleting all records for `+emailAddress+``);
for (const rId of recordIds) {
const response = await axios.delete(`${process.env.API_URL}/`+userId+`/records/`+recordIds+``, {'headers': {Authorization: 'Bearer '+accessToken+''}});
}
return response;
}
catch(e) {
console.error(``+emailAddress+` produced the Record Delete Error = ` + e);
}
}
This isn't working, and I'm unsure why. I would like to see the response for each axios.delete call, but I'm not sure how to get that. Currently its returning as response undefined.
Why your code didn't work:
const response is declared inside the loop scope, and is not accessible out of this closure.
Even if it was defined before the loop (using let const), and assigned inside the loop, you would still be able to return only the last response.
You can push each response to an array (responses), and return the array:
async function DeleteAllRecords (emailAddress) {
try {
var accessToken = await setup.getAccessToken(emailAddress);
var userId = await user.getUserId(emailAddress);
var recordIds = await getAllRecordID(emailAddress);
console.log(`Deleting all records for `+emailAddress+``);
const responses = [];
for (const rId of recordIds) {
const response = await axios.delete(`${process.env.API_URL}/`+userId+`/records/`+recordIds+``, {'headers': {Authorization: 'Bearer '+accessToken+''}});
responses.push(response);
}
return responses;
}
catch(e) {
console.error(``+emailAddress+` produced the Record Delete Error = ` + e);
}
}
However, in this case multiple parallel requests would be better, since you don't actually need to delete one by one. I would use Array.map() to iterate the recordIds array, and return a promise for each one, then wait for all responses using Promise.all(), which would also return an array of responses:
async function DeleteAllRecords (emailAddress) {
try {
var accessToken = await setup.getAccessToken(emailAddress);
var userId = await user.getUserId(emailAddress);
var recordIds = await getAllRecordID(emailAddress);
console.log(`Deleting all records for `+emailAddress+``);
return Promise.all(recordIds.map(rId => axios.delete(`${process.env.API_URL}/`+userId+`/records/`+recordIds+``, {'headers': {Authorization: 'Bearer '+accessToken+''}})));
}
catch(e) {
console.error(``+emailAddress+` produced the Record Delete Error = ` + e);
}
}
This isn't working, and I'm unsure why. I would like to see the response for each axios.delete call, but I'm not sure how to get that. Currently its returning as response undefined.
There are several issues in your code:
const response declared within loop block, but you try to return it after the loop. const and let are strictly block scoped, thus by referring to response after the loop block basically tells JS to return an undefined variable.
You write several times to response. If the issue above wasnt in place, it would still not work correctly, since you only would end up with the response of the last loop run. Here you'd have to collect the response from all runs, e.g. into a list.
Related
Having this code:
const fs = require('fs')
const file = 'books.json';
class Book{
constructor(code) {
this._code = code;
}
get code() {
return this._code;
}
set code(value) {
this._code = value;
}
}
async function writeBooks(){
const data = JSON.stringify([new Book('c1'), new Book('c2')]);
await fs.promises.writeFile(file, data, 'utf8');
}
async function getBook(code){
try{
const data = await fs.promises.readFile(file);
const array = JSON.parse(data);
return array.find(b => b.code === code);
} catch (err){
console.log(err)
}
}
writeBooks();
getBook('c1').then(b => console.log(b));
I am getting undefined (instead of the expecting book object).
How to get the object (the above problem)
If async function always returns promise, how can I then return object for the client, instead of him having to call then() from the getBook(code)?
do I need to await for the fs.promises.writeFile()? as I am doing in writeBooks()? As fas as I understand the async/await now, is that the return value from await function is the data or error. But since the writeFile() does not returns anything, or error at most (as opposed to readFile()) why would I want to await for no data?
Actually the root of problem is not about async/awaits or promises. The problem is trying to write an array to a json file. If you write your json data like the code snippet below (as a key-value pair), your problem is solved.
{"1": [new Book('c1').code, new Book('c2').code]} //as a key-value pair
const fs = require('fs')
const file = 'books.json';
class Book{
constructor(code) {
this._code = code;
}
get code() {
return this._code;
}
set code(value) {
this._code = value;
}
}
async function writeBooks(){
const data = JSON.stringify({"1": [new Book('c1').code, new Book('c2').code]});
await fs.promises.writeFile(file, data, 'utf8');
}
async function getBook(code){
try{
const data = await fs.promises.readFile(file);
const dataOnJsonFile = JSON.parse(data);
return dataOnJsonFile["1"];
} catch (err){
console.log(err)
}
}
writeBooks();
getBook('c1').then(b => console.log(b));
The above problem is that the Books returned from JSON.parse have only data, not methods, and thus I cannot get the code via get code(){}, but only as public parameter of class Book as book._code, which however breaks encapsulation (convetion is that _[propery] is private, and there should be appropriate getters/setters). So I made the properties public (and broke encapsulation), because I still don't know, how to assign methods to object created from JSON.
No, the result of async is always Promise. You cannot unwrap it inside async, the client will always have to unwrap it. (so await fs.promises.WriteFile() will unwrap it, but then immediately wrap it back, before async function returns.
as explained above.
I'm trying to embed multiple videos to a web page using Vimeo's oEmbed. The idea is to simply enter the url in the CMS which will generate a div for each item containing the code below.
This javascript is doing what I want but only works with the first item. When I check the console there's only one response which contains the JSON metadata for the first item/video.
Probably this is not the best method but is getting the job done, all I need is to make it work for multiple items. Any ideas how can I do that?
Thank you
<div class="vimeo-video" id="[[+ID]]-video"></div>
<div class="vimeo-info" id="[[+ID]]-info"></div>
<script>
const getJSON = async url => {
try {
const response = await fetch(url);
if (!response.ok) // check if response worked (no 404 errors etc...)
throw new Error(response.statusText);
const data = await response.json(); // get JSON from the response
return data; // returns a promise, which resolves to this data value
} catch (error) {
return error;
}
}
console.log("Fetching data...");
getJSON("https://vimeo.com/api/oembed.json?url=[[+myVideoURL]]").then(data => {
document.getElementById("[[+ID]]-video").innerHTML = data.html;
document.getElementById("[[+ID]]-info").innerHTML = '<h2>' + data.title + '</h2>' + data.description;
console.log(data);
}).catch(error => {
console.error(error);
});
</script>
In case somebody with basic javascript skills like me goes through something similar. The problem was a rookie's mistake, I had to use var instead of const.
The reason is because var variables can be updated and re-declared but const variables can neither be updated nor re-declared. So here's the working code:
var getJSON = async (url) => {
try {
var response = await fetch(url);
if (!response.ok)
// check if response worked (no 404 errors etc...)
throw new Error(response.statusText);
var data = await response.json(); // get JSON from the response
return data; // returns a promise, which resolves to this data value
} catch (error) {
return error;
}
};
Summary
I'd like to collate paginated output into an array using JavaScript's Fetch API recursively. Having started out with promises, I thought an async/await function would be more suitable.
Attempt
Here's my approach:
global.fetch = require("node-fetch");
async function fetchRequest(url) {
try {
// Fetch request and parse as JSON
const response = await fetch(url);
let data = await response.json();
// Extract the url of the response's "next" relational Link header
let next_page = /<([^>]+)>; rel="next"/g.exec(response.headers.get("link"))[1];
// If another page exists, merge it into the array
// Else return the complete array of paginated output
if (next_page) {
data = data.concat(fetchRequest(next_page));
} else {
console.log(data);
return data;
}
} catch (err) {
return console.error(err);
}
}
// Live demo endpoint to experiment with
fetchRequest("https://jsonplaceholder.cypress.io/posts?_page=9");
For this demo, it should result in 2 requests which yield a single array of 20 objects. Although the data is returned, I can't fathom how to collate it together into an array. Any guidance would be really appreciated. Thanks for your time.
Solution #1
Thanks to #ankit-gupta:
async function fetchRequest(url) {
try {
// Fetch request and parse as JSON
const response = await fetch(url);
let data = await response.json();
// Extract the url of the response's "next" relational Link header
let next_page;
if (/<([^>]+)>; rel="next"/g.test(response.headers.get("link"))) {
next_page = /<([^>]+)>; rel="next"/g.exec(response.headers.get("link"))[1];
}
// If another page exists, merge its output into the array recursively
if (next_page) {
data = data.concat(await fetchRequest(next_page));
}
return data;
} catch (err) {
return console.error(err);
}
}
fetchRequest("https://jsonplaceholder.cypress.io/posts?_page=9").then(data =>
console.log(data)
);
For each page, subsequent calls are made recursively and concatenated together into one array. Would it be possible to chain these calls in parallel, using Promises.all, similar to this answer?
On a side note, any ideas why StackOverflow Snippets fails on the second Fetch?
You need to wrap next_page in a condition, otherwise it will lead to type error on the last call (Since /<([^>]+)>; rel="next"/g.exec(response.headers.get("link")) will be null)
Before concating data, you need the promise to get resolved.
Making some minor changes to your code can result in the correct output:
global.fetch = require("node-fetch");
async function fetchRequest(url) {
try {
// Fetch request and parse as JSON
const response = await fetch(url);
let data = await response.json();
// Extract the url of the response's "next" relational Link header
let next_page;
if(/<([^>]+)>; rel="next"/g.exec(response.headers.get("link")))
next_page = /<([^>]+)>; rel="next"/g.exec(response.headers.get("link"))[1];
// If another page exists, merge it into the array
// Else return the complete array of paginated output
if (next_page) {
let temp_data = await fetchRequest(next_page);
data = data.concat(temp_data);
}
return data;
} catch (err) {
return console.error(err);
}
}
// Live, demo endpoint to experiment
fetchRequest("https://jsonplaceholder.cypress.io/posts?_page=9").then(data => {
console.log(data);
});
I have a system where I need an id from a server to handle events. I should only fetch the id if/when the first event happens, but after that, I need to use the same id for each subsequent event. I know how to use async-await etc. so I have some code like this
var id = "";
async function handleEvent(e) {
if (! id ) {
let response = await fetch(URL)
if (response.ok) {
let json = await response.json();
id = json.id ;
}
}
// use id to handle event
}
But my problem is that I could receive multiple events before I receive a response, so I get multiple overlapping calls to fetch a new id.
How can I have multiple asynchronous calls to handleEvent, with the first one processing the fetch and any subsequent call waiting for it to complete to access the result?
Create a function to ensure you only make one request for the id using a lazy promise.
const URL = 'whatever'
let idPromise // so lazy 🦥
const getId = async () => {
const response = await fetch(URL)
if (!response.ok) {
throw response
}
return (await response.json()).id
}
const initialise = () {
if (!idPromise) {
idPromise = getId()
}
return idPromise
}
// and assuming you're using a module system
export default initialise
Now all you have to do is prefix any other call with initialise() to get the ID which will only happen once
import initialise from 'path/to/initialise'
async function handleEvent(e) {
const id = await initialise()
// do stuff with the ID
}
The currently accepted response relies on a global variable, which is not ideal. Another option is to use a class.
class IDManager {
getId(URL) {
if (this.id) {
return this.id;
}
this.id = fetch(URL)
return this.id
}
}
Then when you call getId, you simply await the result. If no previous request has been made, a network request will be sent. If there is already a pending request, every call will await the same result. If the promise is already resolved, you will get the result immediately.
const idManager = new IDManager();
async function handleEvent() {
const id = await idManager.getId(URL);
// Do stuff with the ID.
}
Not clear why your function is parameterized by "e".
I would write it in a more straightforward manner:
async function request(URL) {
let response = fetch(URL)
if (response.ok) {
let json = await response.json();
return json.id;
}
return false;
}
Then if the sequence of your calls matters write them one by one.
If not then you could use Promise.all (Promise.allSettled maybe) to run them all at once.
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
The solution to this turned out to be a little different from the previous answers. I thought I would post how I made it work in the end. The answers from #phil and #vaelin really helped me to figure this out.
Here was my solution...
class IDManager {
async fetchID (resolve,reject ) {
const response = await fetch( URL, { } ) ;
const id = await response.json() ;
resolve( id );
}
async getID() {
if ( this.id === undefined ) {
if ( this.promise === undefined ) {
var self = this;
this.promise = new Promise( this.fetchID ).then( function(id) { self.id = id;} );
}
await this.promise;
}
return this.id;
}
}
The problem was that awaiting the fetch the getID call took a couple of seconds. During that time there were often multiple calls to getID, all of which initiated another fetch. I avoided that by wrapping the fetch and response.json calls in another promise which was created instantly, and so avoided the duplicates.
I am trying to capture the response of two service calls within a function. Got to know that async and await will solve this purpose and tried below. Here inside async function ex - I am making a call to users, companies end point and console log is displaying perfect, but while retrieving the same value by calling the async function is giving Promise Pending. I tried two options 1. by simply calling the async function - giving Promise Pending 2. by calling with await prefixed - giving await is a reserved word.
Please let me know how to capture the response from this...
const service = {
getUsers: () => axios.get(`http://localhost:3000/users`),
getCompanies: () => axios.get('http://localhost:3000/companies')
};
let ex = async () => {
let users = {};
let companies = {};
try {
users = await service.getUsers()
companies = await service.getCompanies()
console.log('Example ', {
users: users.data,
companies: companies.data
})
} catch (err) {
console.log(err);
}
return [{ users, companies}];
};
//let resp = await ex(); - giving await is a reserved word
// let resp = ex(); - giving Promise is pending..
console.log(resp);
All async functions will always return a promise. If you return nothing, the function will return a promise for undefined. Whatever you return will get wrapped up in a promise, which you need to await or call then on to access the value inside.
resp.then(console.log)