【问题标题】:Write a loop around async await that will read and write a files in parallel?围绕异步等待编写一个循环,它将并行读取和写入文件?
【发布时间】:2017-02-08 13:35:51
【问题描述】:

我正在使用fsphantomJS

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

我有 4 条路线(网址)从 phantom JS 打开。打开时,会读取页面内容,然后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`);
    });
  })
};

【问题讨论】:

    标签: node.js asynchronous async-await phantomjs


    【解决方案1】:

    我花了一段时间才在支持awaitasync 的环境中真正启动并运行它。事实证明 Node v7.5.0 支持它们——比使用 babel 更简单!这次调查中唯一的另一个问题是,我用来测试的request-promise 在没有正确构建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 语法,您还应该能够在不声明承诺的情况下执行 fsPromise() 函数:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-01
      • 2016-12-25
      • 1970-01-01
      • 2021-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      相关资源
      最近更新 更多