Node.js 围绕async await编写一个循环,该循环将并行读取和写入文件?
我使用的是Node.js 围绕async await编写一个循环,该循环将并行读取和写入文件?,node.js,asynchronous,async-await,phantomjs,Node.js,Asynchronous,Async Await,Phantomjs,我使用的是fs和phantomJS const phantom = require('phantom'); const fs = require('fs'); 我有4条从phantom JS打开的路由(URL)。打开时,读取页面内容,然后node.fs将该内容写入自己的html文件中 const routes = [ 'about', 'home', 'todo', 'lazy', ] 问题: 如何对const routes中的每个值并行循环此异步函数。 (async f
fs
和phantomJS
const phantom = require('phantom');
const fs = require('fs');
我有4条从phantom JS打开的路由(URL)。打开时,读取页面内容,然后node.fs
将该内容写入自己的html文件中
const routes = [
'about',
'home',
'todo',
'lazy',
]
问题:
如何对
const routes
中的每个值并行循环此异步函数。
(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`);
});
})
};
我花了一段时间才让它在支持
await
和async
的环境中实际启动和运行。事实证明,节点v7.5.0支持它们——比使用巴贝尔更简单!本次调查中唯一的另一个棘手问题是,我用来测试的请求允诺
,在允诺没有正确构建时,似乎不会优雅地失败。当我尝试使用wait
时,我看到了很多类似这样的错误:
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语法,因此还应该能够在不声明承诺的情况下执行fsPromise()
函数:
async const fsPromise = (file, str) => {
return await fs.writeFile(file, str)
}