async在await循环中使用是否有任何问题?我正在尝试循环遍历文件数组和forEach每个文件的内容.
import fs from 'fs-promise'
async function printFiles () {
const files = await getFilePaths() // Assume this works fine
files.forEach(async (file) => {
const contents = await fs.readFile(file, 'utf8')
console.log(contents)
})
}
printFiles()
Run Code Online (Sandbox Code Playgroud)
这段代码确实有效,但这可能会出错吗?我有人告诉我你不应该使用await这样的高阶函数,所以我只是想问一下这是否有任何问题.
您好,我有一个 url 由 javascript 呈现的网站。我想在我的网站中找到所有脚本标签,然后找到数学脚本 src 并只返回有效的标签。接下来找到脚本的父级,最后点击链接。这就是我所拥有的:
const scripts = await page.$$('script').then(scripts => {
return scripts.map(script => {
if(script.src.indexOf('aaa')>0){
return script
}
});
});
scripts.forEach(script => {
let link = script.parentElement.querySelector('a');
link.click();
});
Run Code Online (Sandbox Code Playgroud)
我的问题是我有 script.src 未定义。当我删除该条件时,我移动到 forEach 循环,但我得到 querySelector 未定义。我可以在调试模式控制台内的 js 中编写该代码,但我无法将其移动到 Puppeteer API。
从控制台我得到预期的结果
let scripts = document.querySelectorAll('script');
scripts.forEach(script=>{
let el = script.parentElement.querySelector('a');
console.log(el)
})
Run Code Online (Sandbox Code Playgroud) 所以我想做的是用我的谷歌个人资料打开 puppeteer 窗口,但我想要的是多次执行它,我的意思是 2-4 个窗口但具有相同的个人资料 - 这可能吗?当我这样做时,我收到此错误:
(node:17460) UnhandledPromiseRejectionWarning: Error: Failed to launch the browser process!
[45844:13176:0410/181437.893:ERROR:cache_util_win.cc(20)] Unable to move the cache: Access is denied. (0x5)
Run Code Online (Sandbox Code Playgroud)
(node:17460) UnhandledPromiseRejectionWarning: Error: Failed to launch the browser process!
[45844:13176:0410/181437.893:ERROR:cache_util_win.cc(20)] Unable to move the cache: Access is denied. (0x5)
Run Code Online (Sandbox Code Playgroud) 在node.js中,我需要使用一个function procesMultipleCandidates ()包含Array.foreach 的1,该进程将每个元素插入db。但整个功能应在完成所有插入操作后返回响应
JavaScript代码
async function procesMultipleCandidates (data) {
let generatedResponse = []
await data.forEach(async (elem) => {
try {
// here candidate data is inserted into
let insertResponse = await insertionInCandidate(elem)
//and response need to be added into final response array
generatedResponse.push(insertResponse)
} catch (error) {
console.log('error'+ error);
}
})
console.log('complete all') // gets loged first
return generatedResponse // return without waiting for process of
}
Run Code Online (Sandbox Code Playgroud)
并且如上所述,最后一个return语句不等待foreach执行首先完成。