猿问

将数据异步写入承诺内的 GCS

我试图找到一种方法,将json数据写入Google Cloud Storage存储桶中的文件,在承诺内。


我发现,如果我尝试将值逐个推送到数组,然后返回,它只给我数组的前3个结果(而控制台.log将返回所有内容)。


如果我尝试在本地范围内编写一些东西,它只返回数组中的最后一个值(并覆盖所有以前的值而不是附加它们)。


因此,从本质上讲,我的问题是:有没有办法编写一个承诺或类似的东西来等待所有循环值被收集起来,一旦完成,就将这些值返回到一个函数,然后该函数将其全部上传到GCS?


或者,有没有办法在抓取数据的同时,将这些值异步写入GCS中的.json文件?


const urls = [/* 20+ URLs go here... */];

let promises = [];


// Build array of Promises

urls.map(function(url) {

  promises.push(axios.get(url));

});


// Map through the array of promises and get the response results

axios.all(promises).then((results) => {

  results.map((res) => {

    try {

      // Scrape the data

      const $ = new JSDOM(res.data);

      const data = {};


      data.title = ($.window.document.querySelector('head > title') !== null ? $.window.document.querySelector('head > title').text : '');

      data.description = ($.window.document.querySelector("meta[name='description']") !== null ? $.window.document.querySelector('meta[name="description"]').content : '');

      data.robots = ($.window.document.querySelector("meta[name='robots']") !== null ? $.window.document.querySelector("meta[name='robots']").content : '');


      const value = JSON.stringify(data) + '\n';


      // Tried array.push(value) here but doesn't return all the values?

      // Any way to return all the values and then bulk upload them to GCS outside of this code block?

      const file = storage.bucket(bucketName).file(filename);

      file.save(value, function(err) {

        if (!err) {

          // file written

        }

      })


    } catch(e) {

      console.log(e);

    }

  })

})

很抱歉解释得很差,基本上我不能将所有值推送到一个数组,然后上传它,如果我尝试逐个上传值,我只得到循环数组中的最后一个值。


注意:我不会尝试使用fs.writeFile()将数据保存到本地的.json文件中,然后上传到GCS,而是将JSON数据直接发送到GCS,而无需中间的步骤。


拉丁的传说
浏览 83回答 1
1回答

四季花海

如果我正确地理解了你需要什么,它应该工作axios.all(promises).then((results) => {  const uploads = results.map((res) => {    try {      // Scrape the data      const $ = new JSDOM(res.data);      const data = {};      data.title = ($.window.document.querySelector('head > title') !== null ? $.window.document.querySelector('head > title').text : '');      data.description = ($.window.document.querySelector("meta[name='description']") !== null ? $.window.document.querySelector('meta[name="description"]').content : '');      data.robots = ($.window.document.querySelector("meta[name='robots']") !== null ? $.window.document.querySelector("meta[name='robots']").content : '');      const value = JSON.stringify(data) + '\n';      return new Promise((resolve, reject) => {       const file = storage.bucket(bucketName).file(filename);       file.save(value, function(err) {         if (!err) {           resolve()         }         reject()       })      });    } catch(e) {      console.log(e);    }  })  return Promise.all(uploads);})
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答