简体   繁体   中英

How to call a function when something is done

I am trying to make it so when the query is done, and the data array is full, it should then do the res.send() part.

This code is currently failing -- the sendData function runs before the query is done:

function showPostsOnPage(pageNumber, nPerPage) {
  funnyPosts.find().skip((pageNumber-1)*nPerPage).limit(nPerPage).each( function(err, post) {
    data.push(post);
  });
  sendData(data);
}

function sendData(data) {
  res.send(
    { msg: '', data: data } // Alerts empty on the client side.
  );    
}

On the client side I use:

var pageNumber = {
  'pageNumber': 30
};

$.ajax({
  type: 'POST',
  data: pageNumber,
  url: '/nextHomeImages'
}).done(function( response ) {
  if (response.msg === '') {
    alert(response.data);
  } else {
    console.log('Error: ' + response.msg);
  }
});

I noticed keyword each which to me jumped as jQuery.

With that said there is a finite length. I would do something like:

var len;
function showPostsOnPage(pageNumber, nPerPage) {
  var _posts = funnyPosts.find().skip((pageNumber-1)*nPerPage).limit(nPerPage);
  len = _posts.length;
  _posts.each( function(err, post) {
    data.push(post);
    len --;
    if (len <= 0) sendData(data);
  });
  //sendData(data);
}

function sendData(data) {
  res.send(
    { msg: '', data: data } // Alerts empty on the client side.
  );    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM