简体   繁体   中英

How to call external function inside callback in nodejs

Calling a external functions in nodejs as we do in javascript so that we can re-use the function but in my case its not working. Why?

I am guessing its working asynchronously in nodejs. How do I fix this? Callbacks? I am new to nodejs.

app.get('/googleSyncCallback', passport.authenticate('google', {
  failureRedirect: 'url'
}),

function(req, res) {

  var contacts = new GoogleContacts({
    token: req.token
  });
  var retrievedContacts = '';
  var retrievedContactsArr = [];

  contacts.getContacts(function(err, contacts) {
    contacts.forEach(function(entry) {
      retrievedContacts = {
        contact: {
          "phone": {
            "cell": entry.phoneNumber,
          }
        },
      }
      retrievedContactsArr.push(retrievedContacts);
      console.log('array... ', retrievedContactsArr[0]); //prints all values
    });
  });
  checkIfContactExists(req, res, retrievedContactsArr);
}
});

function checkIfContactExists(req, res, retrievedContactsArr) {
  //PRINTS UNDEFINED..
  console.log('array... ', retrievedContactsArr[0]); //// LINE 10
}

printing the array retrievedContactsArr[0] is returning undefined at line 10.

You need to change to put your function inside the callback, you also need to add a callback to the function, as express can define middleware with the signature (req, res) that must run synchronously or return a promise or have the signature (req, res, next) where next is a callback.

app.get('/googleSyncCallback', passport.authenticate('google', {
  failureRedirect: 'url'
}),

function(req, res, next) {

  var contacts = new GoogleContacts({
    token: req.token
  });
  var retrievedContacts = '';
  var retrievedContactsArr = [];

  contacts.getContacts(function(err, contacts) {
    contacts.forEach(function(entry) {
      retrievedContacts = {
        contact: {
          "phone": {
            "cell": entry.phoneNumber,
          }
        },
      }
      retrievedContactsArr.push(retrievedContacts);
      console.log('array... ', retrievedContactsArr[0]);
      checkIfContactExists(req, res, retrievedContactsArr);
      next()
    });
  });

    }
    });

    function checkIfContactExists(req, res, retrievedContactsArr) {
      //PRINTS UNDEFINED..
      console.log('array... ', retrievedContactsArr[0]); //// LINE 10
    }

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