aws lambda nodejs在另一个异步函数中访问异步函数的值

时间:2017-02-22 12:25:38

标签: javascript asynchronous firebase aws-lambda alexa-skills-kit

我有一个函数,我在其中获取firebase数据值,即contact:

function firebaseData (callback) {
  if(firebase.apps.length == 0) {
    firebase.initializeApp({
      serviceAccount: "./Sample1-bc6d1ce099d8.json",
      databaseURL:"https://sample1-74bc2.firebaseio.com/"
    });
  }
  var ref = firebase.database().ref();
  var usersRef = ref.child('users');

  usersRef.once('value').then(function (snap) {  
    snap.forEach(function(childSnapshot) {
      var childKey = childSnapshot.val();
      var contact = childKey.Contact;
      callback(contact)  
    });
  });
}

我想要的是在CONTACT:

的其他功能中使用此联系值数据
function getContactFromSession(intent, session, callback) {
  const repromptText = null;
  const sessionAttributes = {};
  let shouldEndSession = false;
  let speechOutput = "amy's contact is"+CONTACT;

  // Setting repromptText to null signifies that we do not want to reprompt the user.
  // If the user does not respond or says something that is not understood, the session
  // will end.

   callback(
    sessionAttributes,
    buildSpeechletResponse(intent.name, speechOutput, repromptText, shouldEndSession)
   );    
}

怎么可以这样做,有人可以建议我吗?

1 个答案:

答案 0 :(得分:0)

也许是这样的?在getContactFromSession()的回调中调用firebaseData()的回调。

function getContactFromSession(intent, session, callback) {
  const repromptText = null;
  const sessionAttributes = {};
  let shouldEndSession = false;

  firebaseData(function (contact) {
    let speechOutput = "amy's contact is " + contact;
    callback(
      sessionAttributes,
      buildSpeechletResponse(intent.name, speechOutput, repromptText, shouldEndSession)
     );
  })    
}

使用Promise可能有助于提高其可读性。