在主代码中我多次使用这个片段:
(async() => {
(somethning code)
try {
await page.waitForSelector('.css123', {timeout: 5000});
} catch (e) {
console.log(error);
}
try {
await page.click('.css123');
} catch (e) {
console.log(error);
}
}
(somethning code)
}
如何在函数中正确声明此代码并在主代码中使用此函数?我尝试了“const save = async() => {}”和“function save() {}” - 它不起作用。
声明函数有两种方法,您已经提到过它们。
const myFunc = () => {}
和 function myFunc() {}
// Define the function
const save = async (page) => {
try {
await page.waitForSelector('.css123', { timeout: 5000 });
} catch (error) {
console.log(error);
}
try {
await page.click('.css123');
} catch (error) {
console.log(error);
}
};
// Call the function in your main code
(async () => {
// (some code)
// Ensure `page` is passed to the `save` function
await save(page);
// (some other code)
})();