gpt4 book ai didi

node.js - 围绕 async wait 编写一个循环来并行读取和写入文件?

转载 作者:太空宇宙 更新时间:2023-11-04 00:27:54 24 4
gpt4 key购买 nike

我正在使用 fsphantomJS

const phantom = require('phantom');
const fs = require('fs');

我有从 phantom JS 打开的4条路线(url)。打开时,会读取页面内容,然后 node.fs 会将该内容写入其自己的 html 文件中。

const routes = [
'about',
'home',
'todo',
'lazy',
]
<小时/>

问题:

<小时/>

如何并行循环此异步函数以获取 const 路由 中的每个值。

(async function() {
const instance = await phantom.create();
const page = await instance.createPage();
const status = await page.open(`http://localhost:3000/${routes}`);
const content = await page.property('content');

await fsPromise(`${routes}.html`, content);

await instance.exit();
}());

const fsPromise = (file, str) => {
return new Promise((resolve, reject) => {
fs.writeFile(file, str, function (err) {
if (err) return reject(err);
resolve(`${routes} > ${routes}.html`);
});
})
};

最佳答案

我花了一段时间才在支持 awaitasync 的环境中实际启动并运行它。事实证明 Node v7.5.0 支持它们 - 比与 babel 战斗简单得多!这项调查中唯一的另一个棘手问题是,当 Promise 未正确构建时,我用来测试的 request-promise 似乎不会优雅地失败。当我尝试使用 await 时,我看到了很多这样的错误:

return await request.get(options).map(json => json.full_name + ' ' + json.stargazers_count);
^^^^^^^
SyntaxError: Unexpected identifier

最后,我意识到你的 Promise 函数实际上并没有使用 async/await (这就是我的错误的原因),所以前提应该是相同的。这是我进行的测试——它与你的非常相似。关键在于同步 for() 迭代:

var request = require('request-promise')
var headers = { 'User-Agent': 'YOUR_GITHUB_USERID' }
var repos = [
'brandonscript/usergrid-nodejs',
'facebook/react',
'moment/moment',
'nodejs/node',
'lodash/lodash'
]

function requestPromise(options) {
return new Promise((resolve, reject) => {
request.get(options).then(json => resolve(json.full_name + ' ' + json.stargazers_count))
})
}

(async function() {
for (let repo of repos) {
let options = {
url: 'https://api.github.com/repos/' + repo,
headers: headers,
qs: {}, // or you can put client_id / client secret here
json: true
};
let info = await requestPromise(options)
console.log(info)
}
})()

虽然我无法测试它,但我很确定这会起作用:

const routes = [
'about',
'home',
'todo',
'lazy',
]

(async function() {
for (let route of routes) {
const instance = await phantom.create();
const page = await instance.createPage();
const status = await page.open(`http://localhost:3000/${route}`);
const content = await page.property('content');

await fsPromise(`${route}.html`, content);

await instance.exit();
}
}())

由于您使用的是 ES7 语法,因此您还应该能够在不声明 Promise 的情况下执行 fsPromise() 函数:

async const fsPromise = (file, str) => {
return await fs.writeFile(file, str)
}

关于node.js - 围绕 async wait 编写一个循环来并行读取和写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42102095/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com