首页 > 解决方案 > Firebase 云功能总是在日志中超时

问题描述

我正在使用此链接中的代码:https ://codelabs.developers.google.com/codelabs/firebase-cloud-functions/#9

并且总是在云功能的日志中超时,这是一个代码:

exports.sendPatrola = functions.database.ref('/test/tmp')
.onUpdate((change, context) => {

const original = change.after.val();

var payload = {
data: {
id: String(original.id),
x: String(original.x),
y: String(original.y),
dat: String(original.dat)
}
};

 var options = {
  priority: 'high',
 contentAvailable: true, 
 timeToLive: 60 * 1
};



let tokens = []; // All Device tokens to send a notification to.
// Get the list of device tokens.
return admin.database().ref('keys').once('value').then((allTokens) => {
if (allTokens.val()) {
  // Listing all tokens.
  tokens = Object.keys(allTokens.val());

  // Send notifications to all tokens.
  return admin.messaging().sendToDevice(tokens, payload, options);
}
return {results: []};
}).then((response) => {
return cleanupTokens(response, tokens);
}).then(() => {
console.log('Notifications have been sent and tokens cleaned up.');
return null;
});
 }

错误消息是:函数执行耗时 60002 毫秒,完成状态:“超时”

这里有什么问题?

标签: firebasefirebase-cloud-messaginggoogle-cloud-functions

解决方案


请尝试这种方式,该函数cleanupTokens应该返回一个承诺:

exports.sendPatrola = functions.database.ref('/test/tmp').onUpdate((change, context) => {
  const original = change.after.val();
  var payload = {
    data: {
      id: String(original.id),
      x: String(original.x),
      y: String(original.y),
      dat: String(original.dat)
    }
  };
  var options = {
    priority: 'high',
    contentAvailable: true,
    timeToLive: 60 * 1
  };
  let tokens = [];
  return admin.database().ref('keys').once('value').then((allTokens) => {
    if (allTokens.val()) {
      tokens = Object.keys(allTokens.val());
      return admin.messaging().sendToDevice(tokens, payload, options);
    } else {
      const result = [];
      return result;
    }
  }).then((response) => {
    return cleanupTokens(response, tokens);
  }).then(() => {
    console.log('Notifications have been sent and tokens cleaned up.');
    return null;
  });
});

推荐阅读