0

I am trying to post the data to the database .then query the database for the last 3 entries .then res.send all of the data to ajax/console.log.

However If I empty the database collection on my first button click, it will grab and post the data to mongodb collections, however res.send will send an empty json array before its finished so the consolelog is empty and the html display is blank.

(Note: I did check after first button press to make sure there was data inside: I'm figuring that it's probably not grabbing the latest of existing data, not the ones that were just pushed into the collection database ex id3-6 instead of id7-9, I'm uploading news articles 3 at a time, so when I test the titles are duplicates every time.

When I click it a second time, it has data waiting already in the database so, it will load up and display data then, but unsure why the promise is not working. Also the resolve is working.

const express = require('express');
const {grabArticles} = require('../controller/scrapper.js');
const Article = require('../models/articles');
const Current = require('../models/current');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
// const Comments = require('../models/comments');

// variables
const router = express.Router();


router.get('/api/fetch', (err, res) => {
  const promiseInfo = new Promise((resolve, reject) => {
    if ( grabArticles() === undefined ) {
      console.log('hurrayyyy');
      resolve();
    } else {
      console.log('oh nooooooo!');
      reject();
    }
  });

  promiseInfo.then(() => {
    Current.find({}, 'topic title', (err, data) => {
    }).limit(3)
      // gives the last three articles saved in current models
      .sort({createdAt: 'desc'})
      .then((data) => {
        res.send({response: data, total: 'Articles were found!'});
        // console.log(data);
    })
  });
});
RandomC
  • 3
  • 6
  • What is `grabArticles()`? Another async function? – Neil Lunn Nov 08 '17 at 04:11
  • yes, sorry its just a function that gets topic and title from a website and save them to Current collections db – RandomC Nov 08 '17 at 04:17
  • As stated, either `grabArticles()` already returns a Promise so it would be simply `grabArticles().then( ) => Current.find()...` or it's a "callback" style function in which case you wrap like `new Promise((resolve,reject) => grabArticles(reject,resolve) ).then( ) => Current.find()....`. Or indeed it's "neither" and it really should be one of those. So you need to read the common reference answer again and understand how this all works. – Neil Lunn Nov 08 '17 at 04:19
  • Paste the code of `grabArticles` too, we can't help you without knowing whats going on with it – nicowernli Nov 08 '17 at 19:32

0 Answers0