I want to call a callback when both forEach are done. I want to know when all of them are done processing asynchronously and call a callback. console.log("Done") seems to finish before the two forEach
const getDates = () => {
const ref = db.ref("reminders");
const dateTime = new Date();
const currentDate = dateFormat(dateTime, "yyyy-mm-dd");
ref
.orderByChild('date')
.endAt(currentDate)
.once('value', (reminderDates) => {
reminderDates.forEach((singleDate) => {
// iterate over reminder dates
singleDate.forEach( (notificationValues) => {
// iterate over notification codes
if (!notificationValues.key.includes('date')) {
processNotifications(notificationValues, () => {
console.log(`Sent notification reminder at ${notificationValues.key}`);
});
}
});
});
}).catch( (error) => {
console.log(error);
});
console.log("Done")
};
Output
Done
AB000001_AB0977 { subtitle: 'Time to start thinking about making a payment',
title: 'School Semester 1, 2019 School Fees',
userId: 'kXnfHPyxfpeLQ1aCjvl8Pu09sssslou1' } d-ktpdo45SQ:APA91bF5rJtaHvtNUE42GDssssXoOAP_r7omRmsIs44WKnABsMC8lintdoDBzUYrZ5lutEKECwuaOOIQtdZkKW5Apt4A0ssssyZwdl_epdI2dYHkhk0h-Yns6jzlMbIltSHasA40YL725sssL9TmyCd
Sent notification reminder at AB000001_AB0977
From the docs:
once
once(eventType: EventType, successCallback?: function, failureCallbackOrContext?: Object | null, context?: Object | null): Promise<DataSnapshot>
once returns a Promise which means it is asynchronous, therefore the console.log("Done") will be printed before your forEach(). You cannot know when the asynchronous operation will be finished.
Therefore, the best way to solve it is to add console.log("Done") inside the forEach():
.once('value', (reminderDates) => {
reminderDates.forEach((singleDate) => {
// iterate over reminder dates
singleDate.forEach( (notificationValues) => {
// iterate over notification codes
if (!notificationValues.key.includes('date')) {
processNotifications(notificationValues, () => {
console.log(`Sent notification reminder at ${notificationValues.key}`);
console.log("Done");
});
}
});
});
I don't realy use firebase but if you want to wait for multiple asynchronus operations you can use Promise.all
You just have to push inside an array all your async operation. Once it's finish juste write something like :
Promise.all(yourArrayOfPromise)
.then(() => {
console.log('success');
})
.catch(err => {
console.log(err);
})
Related
I get problems with async/await functions and changing state in React.
This is my async function, which is triggered by clicking on the button:
async startNewEntry() {
this.addIssue();
let issue_id;
console.log(this.state.timeEntry, "started_timeEntry")
if (this.state.timeEntry?.issue?.id) {
issue_id = this.state.timeEntry?.issue?.id;
} else {
issue_id = (await this.issueService.list()).data[0]?.id;
}
const { data } = await this.timeEntryService.create({
comments: this.state.timeEntry.comments,
issue_id,
spent_on: moment(new Date()).format("YYYY-MM-DD"),
hours: 0.01,
activity_id: this.localStorageService.get("defaultActivityId")
});
In this function I use this.addIssue, which use this.createIssue, which changing my class component state:
addIssue() {
this.projectService.list([]).then(response => {
response.data = response.data.filter((x: any) => x.status === 1);
this.setState(
{
activeProjects: response.data
},
() => {
this.createIssue();
}
);
});
}
createIssue() {
this.issueAddService
.create({
project_id: this.state.activeProjects[0].id,
tracker_id: trakerId,
priority_id: priorityId,
subject: this.state.timeEntry.comments,
description: this.state.timeEntry.comments
})
.then(response => {
let timeEntry = this.state.timeEntry;
timeEntry.issue = response.data;
this.setState({
timeEntry
});
})
.catch(error => {
console.log("error", error);
});
}
As you can see, in my async function I new to have my new State, but actually async function works before my this.addIssue function. I know that question might be little freaky, but Thanks in forward!!
I am not a React expert, but I don't fully understand why there are lot of setState invocations spread around the place.
If you leave the setState to the end of the function, then you might not need to worry about correctly sequencing asynchronous calls to it (although the other answer does show how this can be achieved).
Perhaps invoking it once might make the code clearer. I welcome corrections...
async startNewEntry() {
const activeProjects = await fetchActiveProjects()
const issue = await this.createIssue()
const timeEntry = await createTimeEntry({ issue, comments: this.state.timeEntry.comments })
this.setState({ activeProjects, issue, timeEntry })
}
async fetchActiveProjects() {
const { data } = await this.projectService.list([])
return data.filter(({ status }) => status === 1)
}
async createIssue() {
const { data } = await this.issueAddService.create({
project_id: this.state.activeProjects[0].id,
tracker_id: trakerId,
priority_id: priorityId,
subject: this.state.timeEntry.comments,
description: this.state.timeEntry.comments
})
return data
}
async createTimeEntry({issue, comments}) {
const { data } = await this.timeEntryService.create({
comments,
issue_id: issue?.id || (await this.issueService.list()).data[0]?.id,
spent_on: moment(new Date()).format("YYYY-MM-DD"),
hours: 0.01,
activity_id: this.localStorageService.get("defaultActivityId")
})
return data
}
You can probably speed this up further by parallelizing the first two async calls:
async startNewEntry() {
const [activeProjects, issue] =
await Promise.all([fetchActiveProjects(), this.createIssue()])
const timeEntry = await createTimeEntry({ issue, comments: this.state.timeEntry.comments })
this.setState({ activeProjects, issue, timeEntry })
}
If you want startNewEntry to wait to do its work until after addIssue has done its work, you need to:
Have addIssue return a promise it fulfills when it's finished its work, and
Use await when calling it: await this.addIssue();
If you need startNewEntry to see the updated state, addIssue's promise will need to be fulfilled from the state completion handler callback, like this:
addIssue() {
// *** Return the promise chain to the caller
return this.projectService.list([]).then(response => {
response.data = response.data.filter((x: any) => x.status === 1);
// *** Create a new promise
return new Promise(resolve => {
this.setState(
{
activeProjects: response.data
},
() => {
this.createIssue();
resolve(); // *** Fulfill the promise
}
);
});
});
}
Often, new Promise is an anti-pattern, particularly when you have another promise you can chain from. But in this case, since you need to wait for the callback from setState (which isn't promise-enabled), it's appropriate. (
Note my comment on the question. I think you're setting up an endless loop...
I'm trying to execute a function after a success response of previous function has returned. Have been trying, with different approaches, but still in vain.
I want my service to post newLoan only after the the loanTerms have been added (which is a API call), but doesn't waits for that an execute the next function without the response of previous.
Before posting this question, I already tried different methods, Even though I'm putting my code inside the subscribe method of function. but still I doesn't performs the way I want it.
The problem is that I've list of products, and I've to perform a network operation on each product and then execute my other function, but it only waits for just 1st product, after that I doesn't wait and executes the next function.
Here is my code
{
this.newLoanForm.value.invoiceDate = this.loanDate.format();
document.getElementById('submitButton').style.display = 'none';
// Adding number of months against give loan term ID
let loanProducts = this.loanProductForm.value.products;
let loanTerm;
loanProducts.forEach(product => {
this.loanTermService.getLoanTerm(product.loanTermId).subscribe((response: any) => {
// console.log('Number of months: ', response.numberOfMonths)
loanTerm = response.numberOfMonths;
product.installmentStartDate = this.installmentStartDate.format();
product.monthlyInstallment = product.total / loanTerm;
// I want this function to executed after all the products have been completed their network activity, but it only waits for just 1st product, after that it executes the below code. how do I make it wait for all products.
this.loanService.postLoan(this.newLoanForm.value).subscribe((response: any) => {
console.log('Loan added successfully: ', response);
PNotify.success({
title: 'Loan added Successfully',
text: 'Redirecting to list page',
minHeight: '75px'
})
document.getElementById('submitButton').style.display = 'initial';
this.router.navigate(['searchLoan']);
}, (error) => {
console.log('Error occured while adding loan: ', error);
PNotify.error({
title: 'Error occured while adding loan',
text: 'Failed to add new loan',
minHeight: '75px'
})
document.getElementById('submitButton').style.display = 'initial';
})
}, error => {
console.log('Error while retrieving loanTermId: ', error);
});
});
this.newLoanForm.value.loanProducts = loanProducts;
console.log('Loan Products: ', this.loanProductForm.value);
here's how I tried the above code with promise and async and await
async calculateInstallments() {
// Adding number of months against give loan term ID
this.loanProducts = this.loanProductForm.value.products;
// let loanTerm;
this.loanProducts.forEach(async product => {
console.log('Call to get loanTerms: ', await this.loanTermService.getLoanTermById(product.loanTermId));
let response: any = await this.loanTermService.getLoanTermById(product.loanTermId);
await this.loanProductService.getLoanProductByLoanId(product.loanTermId).then(() => {
let loanTerm = response.numberOfMonths;
console.log('loanTerms', loanTerm);
product.installmentStartDate = this.installmentStartDate.format();
product.monthlyInstallment = product.total / loanTerm;
});
});
}
// putting the function I want to execute after the response of previous in the `then` method
await this.calculateInstallments().then(() => {
this.newLoanForm.value.loanProducts = this.loanProducts;
// Posting loan after the response of loanTerms Service
this.loanService.postLoan(this.newLoanForm.value).subscribe((response: any) => {
console.log('Loan added successfully: ', response);
PNotify.success({
title: 'Loan added Successfully',
text: 'Redirecting to list page',
minHeight: '75px'
});
document.getElementById('submitButton').style.display = 'initial';
this.router.navigate(['searchLoan']);
}, (error) => {
console.log('Error occured while adding loan: ', error);
PNotify.error({
title: 'Error occured while adding loan',
text: 'Failed to add new loan',
minHeight: '75px'
});
document.getElementById('submitButton').style.display = 'initial';
});
});
but it didn't work unfortunately.
I just answered a question today, about almost the same problem. Maybe you still need a solution, otherwise see it as another way to go.
Doesn't mind if you use async await or daisy chain style with new Promise. Since version 3.x of async framework, you'll be able to use the amazing iteration functions (don't know if all) as promise, if you don't use callback.
This is an simple example, how you could use the eachOf function for asynchronously tasks.
const async = require('async');
let items = [
{ firstName: 'John', lastName: 'Doe' },
{ firstName: 'Jane', lastName: 'Doe' },
{ firstName: 'Me', lastName: 'Myself And I' }
];
async.eachOf(items, (item, index, callback) => {
//here you could query db with vaulues from items array as item
console.log('this is item:', item);
new Promise(resolve => {
setTimeout(() => {
resolve(true);
}, 500);
})
.then(result => {
//maybe you need to do something else
console.log('this is the result:', result);
callback();
});
})
.then(() => {
//working ahead with daisy chain
console.log('All items updated');
});
I hope you can work with this setup or it's an inspiration to restructure this and using async await in another handy way.
Good day for all,
I am doing a React course and I'd submited the code to the reviewer. He's returned me few comments and there is one comment I'm not being able to solve.
The comment is the following:
Check if (query === this.state.query) to ensure you are not going to replace the contents to an old response
And part of the code is the one below:
updateQuery = (query) => {
this.setState({
query: query
})
this.updateWantedBooks(query);
}
updateWantedBooks = (query) => {
if (query) {
BooksAPI.search(query).then((wantedBooks) => {
if (wantedBooks.error) {
this.setState({ wantedBooks: [] });
} else {
this.setState({ wantedBooks: wantedBooks });
}
})
} else {
this.setState({ wantedBooks: [] });
}
}
Anyone could help me what do am I suppose to do?
Regards.
Code reviewer is right, you don't really want to replace the response if user has entered the very same query.
You have to store somewhere what for user has searched recently:
this.setState({ wantedBooks: [], query });
In case of success response:
this.setState({ wantedBooks, query });
And then check it in case of further searches:
if (query && query !== this.state.query) {
// continue the search only if query is different that current
Instead of relying on an outer member which is open to abuse by other code, you can employ a factory function to more safely trap a member.
As you have discovered, trapping and testing query == this.state.query can be made to work but is arguably not the best solution available.
With a little thought, you can force each call of updateWantedBooks() automatically to reject the previous promise returned by the same function (if it has not already settled), such that any success callbacks chained to the previous promise don't fire its error path is taken.
This can be achieved with a reusable canceller utility that accepts two callbacks and exploits Promise.race(), as follows:
// reusable cancellation factory utility
function canceller(work, successCallback) {
var cancel;
return async function(...args) {
if (cancel) {
cancel(new Error('cancelled')); // cancel previous
}
return Promise.race([
work(...args),
new Promise((_, reject) => { cancel = reject }) // rejectable promise
]).then(successCallback);
};
};
Here's a demo ...
// reusable cancellation factory utility
function canceller(work, successCallback) {
var cancel;
return async function(...args) {
if (cancel) {
cancel(new Error('cancelled')); // cancel previous
}
return Promise.race([
work(...args),
new Promise((_, reject) => { cancel = reject })
]).then(successCallback);
};
};
// delay utility representing an asynchronous process
function delay(ms, val) {
return new Promise(resolve => {
setTimeout(resolve, ms, val);
});
};
function MySpace() {
// establish a canceller method with two callbacks
this.updateWantedBooks = canceller(
// work callback
async (query) => delay(500, query || { 'error': true }), // a contrived piece of work standing in for BooksAPI.search()
// success callback
(wantedBooks => this.setState(wantedBooks)) // this will execute only if work() wins the race against cancellation
);
this.setState = function(val) {
console.log('setState', val);
return val;
};
};
var mySpace = new MySpace();
mySpace.updateWantedBooks({'value':'XXX'}).then(result1 => { console.log('result', result1) }).catch(error => { console.log(error.message) }); // 'cancelled'
mySpace.updateWantedBooks(null).then(result2 => { console.log('result', result2) }).catch(error => { console.log(error.message) }); // 'cancelled'
mySpace.updateWantedBooks({'value':'ZZZ'}).then(result3 => { console.log('result', result3) }).catch(error => { console.log(error.message) }); // {'value':'ZZZ'} (unless something unexpected happened)
Note that canceller() doesn't attempt to abort the asynchronous process it initiates, rather it stymies the success path of the returned promise in favour of the error path.
I think reviewer's point is that response of Search API is asynchronous and result for "query 1" can arrive after user changed his mind and already requested search "query 2". So when response arrive - we need to check if we really interested in it:
updateQuery = query => {
this.setState({
query: query
wantedBooks: []
})
this.updateWantedBooks(query);
}
updateWantedBooks = query => {
if (query) {
BooksAPI.search(query).then((wantedBooks) => {
// if updateQuery("query1) and updateQuery("query2") called in a row
// then response for query1 can arrive after we requested query2
// => for some period of time we'll show incorrect search results
// so adding check if query still the same can help
if (query !== this.state.query) {
// outdated response
return;
} else if (wantedBooks.error) {
// query is okay, but server error in response
this.setState({
wantedBooks: []
})
} else {
// success response to requested query
this.setState({ wantedBooks });
}
})
}
}
Guys I´ve done some tests with your answers, but I realize that somehow the code was behavioring strangely.
So, I've seen in other part of the reviewer comments, a part which I hadn't had seen before do my answer here, the following comment:
Inside 'then' part of the promise check if(query === this.state.query) to ensure you are not going to replace the contents to an old response.
And this "Inside 'then'" has been beating in my brain.
So, I think I've arrived in a satisfatory code; sure, maybe it isn't the definite solution, that's why I want to show here for you and feel free to comment if I'd have to make some improvement. Here below I put the code:
updateQuery = (query) => {
this.setState({
query: query
})
this.updateWantedBooks(query);
}
updateWantedBooks = (query) => {
if (query) {
BooksAPI.search(query).then((wantedBooks) => {
if (wantedBooks.error) {
this.setState({ wantedBooks: [] });
} else if (query !== this.state.query) {
this.setState( { wantedBooks: [] });
} else {
this.setState({ wantedBooks: wantedBooks });
}
})
} else {
this.setState({ wantedBooks: [] });
}
}
Regards
I have an array of Id' and i need to get the details for each of them.
i currently have this.
const redis = require('redis');
const redisClient = redis.createClient(process.env.REDIS_PORT, process.env.REDIS_HOST);
const arrayList = [
{ id: 3444 },
{ id: 3555 },
{ id: 543666 },
{ id: 12333 },
];
async function getDetails(element) {
await redisClient.hgetall(element.id, (err, user) => {
if (err) {
console.log('Something went wrong');
// Handle Error
return err;
}
console.log('Done for User');
return user;
});
}
arrayList.forEach((element) => {
console.log('element');
await getDetails(element).then((res) => {
// Do Something with response for each element
});
});
This is the response i get right now. its not async. What am i doing wrong please.
element
element
element
element
Done for User
Done for User
Done for User
Done for User
So how things go on in async/await is, you create an async function and inside that function you await for other operations to finish. You call that async function without await OR you wrap it(func call) inside another async function.
arrayList.forEach((element) => {
console.log('element');
let returnedPromise= getDetails(element);
console.log("Promise after getDetails function", returnedPromise);
});
This code change should resolve the error.
Array.forEach() does not wait for promises to execute before moving to the next item.
You could instead use a for-loop in an async function, like so:
async function main() {
for (const element of arrayList) {
const response = await getDetails(element);
// do something with reponse for each element
}
}
main()
.then(() => /* on success */)
.catch((err) => /* on error */);
In parse I have this crazy query where I'm querying on table1 to get an object.
Then querying table2 on a pointer column that matches table1's result for all users that match that.
Next I need to create an object and then create another object using the result of that first object.
Finally save the final object into the users from table2's query.
I'm having an issue chaining everything and for some reason my success message returns before the user objects are saved.
Parse.Cloud.define('startChain', (req, res) => {
let q1 = new Parse.Query("Table1");
q1.equalTo("objectId", req.params.q1ID);
q1.equalTo("user", req.user);
q1.include("user");
q1.get(req.params.q1ID)
.then(post => {
post.get("user")
.then(user => {
// Query on q1
let q2 = new Parse.Query("Table2");
q2.equalTo("t1Object", post);
w2.include("user2");
q2.include("pointer2Object");
q2.find();
})
.then(users => {
var morePromises = users.map(aUser => {
let newObject = new Parse.Object.Extend("Table3");
newObject.set("user", aUser);
newObject.set("table1Pointer", post);
newObject.save()
.then(result => {
var object2 = new Parse.Object.Extend("Table4");
object2.set("column1", aUser);
object2.set("column2", result);
var object3 = new Parse.Object.Extend("Table5");
object2.save()
.then(o2 => {
object3.set('column', 'o2');
object3.save()
.then(o3 => {
aUser.set("o3", o3);
return aUser.save(null, {useMasterKey: true});
});
});
});
});
Promise.all(morePromises)
.then(result => res.success());
})
.catch(err => {
res.error(err.message);
});
});
});
In the first lines
q1.get(req.params.q1ID)
.then(post => {
the argument to then()'s callback is whatever is returned by q1.get().
Following the same logic, you can chain promises on a single level (i.e. not nested) by returning from a chain block what you need in the next. E.g the above could continue like
q1.get(req.params.q1ID)
.then(post => {
...
return q2.find();
}).then( users => {
// users is available here
...
return object2.save();
}).then( o2 => {
});
And so forth...
Ideally you should use async await: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
would be much cleaner, code example below:
async function yourFunction(x) {
const result = await q2.find();
result.map((newObject) => {
await newObject.save();
});
}
not sure your browser support tho.