围绕asynchronous写一个循环,将并行读写文件?

我正在使用fsphantomJS

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

我有4条路线 (url)从幻影JS打开。 当打开时,页面内容被读取,然后node.fs将这些内容写入到它自己的html文件中。

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

题:


如何并行地在const routes中的每个值循环这个asynchronous函数。

 (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的环境中运行。 事实certificate,Node v7.5.0支持他们 – 比与babel战斗更简单! 在这次调查中,唯一的另外一个问题是,我用来testing的request-promise在诺言没有被正确构build时似乎没有优雅地失败。 当我试图用它await时,我看到了很多像这样的错误:

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

最后,我意识到你的promise函数实际上并不使用async / await(这就是我的错误),所以前提应该是一样的。 这是我工作的testing – 和你的testing非常相似。 关键是在同步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) } })() 

虽然我不能testing它,但我确信这会起作用:

 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()下执行fsPromise()函数:

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