I am creating a chrome extension that works in a certain website to automate some tasks in the website, the extension take an array of data and send them one by one (mimic clicking a button in the website that send the data to the backend), so i am automating that async repeating task.
but the problem is that i don't get any data returned from the website after clicking the send button because i am not the owner or the developer that created that website
The website is like a book store, you need to search the book by name then do further work with the book, my extension is about automating this process, so instead of searching the book from the website UI, the extension has many inputs that accept multiple books names then send this collection to the website backend by mimicking clicking a send button in the website UI
My problem here is that i have a function that works with each item in the collection once i click a button in the extension after adding some books names but the problem is that i need to wait in each cycle till the website find the book,so i have asyncronous step here and this is my real problem, i need to wait for the book finding function to complete then i can do the further work
//extension add books button
const addBooks = document.getElementById('add-books');
//books collected from changing the extension inputs
let bookCollection = [{...}, {...}, {...}]
addBooks.addEventListener('click', async () => {
for (let drug of collectedDrugs) {
let { name, code, price } = book;
//trying to await the website find the book
await getBook(name);
await addBook(price, qty);
}
})
Unfortunately this doesn't work and , this function should work with every item in the collection waiting for the async step to finish, complete the function then repeat the same cycle with another book, how can i fix this code to make it work!
CodePudding user response:
You have to move your async function call to a proxy that's outside of the listener because the native eventListener ecosystem is kinda legacy and doesn't support the new async feature:
function getBook(name){
console.log("getBook", name);
}
async function getBookProxy(name){
await getBook(name);
}
document.body.addEventListener('click', () => {
getBookProxy("bob");
});