Reputation: 1539
I'm really confused. I tried to lot of things but I can't reach the correct result.
Here is scenario; I have list of products that I can do multiple choice and delete them one by one. I want to wait all items can be deleted then return me a count.
async delete (ids) {
const res = await this.deleteProcess(ids);
return res;
},
deleteProcess(ids) {
let countS = 0;
Object.assign(ids).map((id) => {
axios({
method: "DELETE",
url: store.getters.getServerPath + "api/v1/product/" + id,
headers: store.getters.getConfigHeaders,
withCredentials: true
}).then(function (response) {
countS++;
}).then(() => {
console.log(countS);
return countS;
});
});
}
And call this function like this:
deleteSelected (id) {
if (id !== undefined) {
this.selectedRows.push(id);
}
controller.delete(this.selectedRows).then(function (res) {
alert(res + " items deleted");
});
},
Result res
is always returns undefined
. But inside of deleteProcess
console.log
is displayed how many items were deleted.
Upvotes: 0
Views: 174
Reputation: 166
Your deleteProcess
method returns nothing, so res
is undefined.
If you want a code using fully the async/await pattern, and delete them one by one, you could do:
async deleteProcess(ids) {
let countSuccess = 0;
let countFailure = 0;
for (const id of ids) {
try {
await axios({
method: "DELETE",
url: store.getters.getServerPath + "api/v1/product/" + id,
headers: store.getters.getConfigHeaders,
withCredentials: true
});
countSuccess++;
} catch (error) {
countFailure++;
}
}
return countSuccess;
}
Upvotes: 0
Reputation: 370729
You should use Promise.all
instead, incrementing countS
each time a response comes back
deleteProcess(ids) {
let countS = 0;
return Promise.all(ids.map((id) => (
axios({
method: "DELETE",
url: store.getters.getServerPath + "api/v1/product/" + id,
headers: store.getters.getConfigHeaders,
withCredentials: true
}).then(function (response) {
countS++;
})
)))
.then(() => countS);
}
But you may as well just count up the length
of ids
rather than keep an external countS
variable:
.then(() => ids.length);
Also note that
Object.assign(ids)
doesn't do anything - the resulting expression is ===
to the original ids
variable, so might as well just use the original variable.
You also might consider adding a catch
when a problem occurs:
controller.delete(this.selectedRows)
.then(function (res) {
console.log(res + " items deleted");
})
.catch((err) => {
console.log('error', err);
});
Upvotes: 2