I’m facing the following difficulty:
I have a process that can be repeated for one or multiple customers.
When it runs for one customer, works well; however when I want to add await logMyResults(var1, var2, var3) I get an error.
I realized it is inside a .then, but on the other side, I need to do a loop on it.
What is the best alternative/solution?
async function questions() {
// Ask questions using inquirer
}
async function logMyResults(pcVar1, pcVar2, pcVar3) {
// Call different processes
}
async function ask() {
await questions().then(() => {
var allcust = require("./customers.json"); // Re-inistialize values .... (lost)
if (genCustomer === "All") {
for (const key of Object.keys(allcust)) {
var objKey = allcust[key];
var objVal = Object.values(objKey);
const [var1, var2, var3] = objVal;
logMyResults(var1, var2, var3) *// CAN NOT PUT await, and it doesn't wait for each process to finish*
}
} else {
if (Object.keys(allcust).includes(genCustomer)) {
var objKey = allcust[genCustomer];
var objVal = Object.values(objKey);
const [var1, var2, var3] = objVal;
logMyResults(var1, var2, var3);
}
}
});
}
ask(); // logMyResults();
When the user selects all customer, the process should wait for logMyResults with all processes to finish, before going to the next customer.
Currently, hits logMyResults, but continues to the next customer (in the loop).
2
Answers
We use only one of the two options await/then and not both of them at the same time.
To solve the issue, you can do this:
Here, the code waits for ‘await questions();’ to finish before executing the rest of the code.
Since you use await, you can remove the
.then()
entirely, and put all the code that’s waiting to execute underawait questions()
.You can do it like so:
To answer your question, if you want to have an await inside a
.then()
, you just need to make the callback function inside the then asynchronous, like so:In this case, you can remove the await.
The
()=>{}
syntax is called an "arrow function", and it works pretty much the same way asfunction name() {}
, except you don’t have to define a name for the function and you don’t have to use the function keyword in your code.