如何从函数内部获取此数组数据返回给我javascript

时间:2017-11-07 06:47:09

标签: javascript jquery arrays scope

我创建了一个承诺,首先运行一个函数来收集数据并将其推送到最初为空的数组。

我已尝试传入一个全局空数组变量,以及此处和那里的小行更改,但我能得到的最好的是未定义没有

是否可能或者我在浪费时间?



router.get('/api/fetch', (err, res) => {
  let results = [];
  // finding all and displaying topic and title, which is the 2nd param
  let promiseInfo = () => {
      return new Promise(function(resolve, reject) {
        grabArticles(results);
        resolve();
      });
  };

  promiseInfo().then(() => {
      //there is nothing that shows here, empty array
      console.log(results);
      res.send({results: results});
  });
});






// function that uses cheerio npm
grabArticles = (results) => {
  results = [];
  console.log('this is passed data: ' + results);
  request("https://fivethirtyeight.com/", function(error, response, html) {
    const $ = cheerio.load(html);
    for (x=1; x<4; x++) {
      // i is the current loop number, element=this is the current data requested
      $('#home-feature-' + x.toString()).each((i, element) => {
        const topic = $(element).children('.post-info').children('.topic').text().trim();
        const title = $(element).children('.post-info').children('.tease-meta').children('.tease-meta-content').children('h2.article-title.entry-title').text().trim();

        const newArticle = {
          topic: topic,
          title: title
        };

        // newArticle.save();
        results.push(newArticle);
      })
    }
    
    //this console.log, has results = 3 objects inside of a results array
    console.log(results);
    return results;
  });
}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

您正在使用Promise

  

Promise对象表示异步操作的最终完成(或失败)及其结果值。

正如文档解释的那样,Promise代表了未来的价值,因此您需要将代码链接到“同一个未来”。

您可以通过使用值调用resolve函数来实现这一目标,然后在“下一个”then上为您提供该值。

类似的东西:

router.get('/api/fetch', (err, res) => {
  let results = [];
  // finding all and displaying topic and title, which is the 2nd param
  let promiseInfo = () => {
      return new Promise(function(resolve, reject) {
        resolve(grabArticles(results));
        // --------------^
      });
  };

  promiseInfo().then((results) => {
  // -------------------^
      //there is nothing that shows here, empty array
      console.log(results);
      res.send({results: results});
  });
});

答案 1 :(得分:0)

您遇到的问题是因为您使用承诺的方式:

grabArticles(results);
resolve();

上面,grabArticles是异步的,所以当它仍在运行时,resolve被执行。所以你解决了这个承诺,但还没有完成异步工作。

见下面的例子:

&#13;
&#13;
router.get('/api/fetch', (err, res) => {
  // finding all and displaying topic and title, which is the 2nd param
  let promiseInfo = () => {
    return new Promise(function(resolve, reject) {
      request("https://fivethirtyeight.com/", function(error, response, html) {
        let results = [];
        const $ = cheerio.load(html);
        for (x = 1; x < 4; x++) {
          // i is the current loop number, element=this is the current data requested
          $('#home-feature-' + x.toString()).each((i, element) => {
            const topic = $(element).children('.post-info').children('.topic').text().trim();
            const title = $(element).children('.post-info').children('.tease-meta').children('.tease-meta-content').children('h2.article-title.entry-title').text().trim();

            const newArticle = {
              topic: topic,
              title: title
            };

            // newArticle.save();
            results.push(newArticle);
          })
        }

        //this console.log, has results = 3 objects inside of a results array
        console.log(results);
        return resolve(results);
      });
    });
  };

  promiseInfo().then(results => {
    //there is nothing that shows here, empty array
    console.log(results);
    res.send({
      results: results
    });
  });
});
&#13;
&#13;
&#13;