5

Tôi mới sử dụng Typecript và tôi đang cố sử dụng chức năng async và await. Tôi nhận được một số thời gian chờ mạng fcm mỗi một lần trong một thời gian và tôi tin rằng nó đã làm với không trả lại lời hứa của tôi một cách chính xác.FCM và Typescript Async await: Network Timing Out

Đây là chức năng đám mây của tôi để gửi thông báo đẩy. Hai chức năng được sử dụng từ khóa đang chờ đợi là incrementBadgeCount, và sendPushNotification:

export const pushNotification = functions.firestore 
    .document('company/{companyId}/message/{messageId}/chat/{chatId}') 
    .onCreate(async event => { 

const message = event.data.data(); 
const recipients = event.data.data().read; 
const messageId = event.params.messageId; 

const ids = []; 
for (const key of Object.keys(recipients)) { 
    const val = recipients[key]; 
    if (val === false) { 
     ids.push(key); 
    } 
} 

return await Promise.all(ids.map(async (id) => { 
    const memberPayload = await incrementBadgeCount(id); 
    const memberBadgeNumberString = 
     memberPayload.getBadgeCount().toString(); 

    const senderName = message.sender.name; 
    const senderId = message.sender.id; 
    const senderMemberName = message.senderMember.name; 
    const toId = message.receiver.id; 
    const text = message.text; 
    const photoURL = message.photoURL; 
    const videoURL = message.videoURL; 
    const dealId = message.dealId; 
    const dealName = message.dealName; 

    const payload = { 
     notification: { 
      title: `${senderName}`, 
      click_action: 'exchange.booth.message', 
      sound: 'default', 
      badge: memberBadgeNumberString 
     }, 
     data: { senderId, toId, messageId } 
    }; 

    const options = { 
     contentAvailable: true 
    } 

    ........ 

    const deviceIDs = memberPayload.getDeviceID() 
    return await sendPushNotification(id, deviceIDs, payload, options); 
    })); 
}); 

Đây là incrementBadgeCount chức năng làm tăng số lượng huy hiệu cho các tải trọng và trả về một số thông tin cho các tải trọng:

async function incrementBadgeCount(memberID: string): 
    Promise<MemberPushNotificaitonInfo> { 
const fs = admin.firestore(); 
const trans = await fs.runTransaction(async transaction => { 
    const docRef = fs.doc(`member/${memberID}`); 
    return transaction.get(docRef).then(doc => { 
      let count: number = doc.get('badgeCount') || 0; 
      const ids: Object = doc.get('deviceToken'); 
      transaction.update(docRef, {badgeCount: ++count}); 
      const memberPayload = new MemberPushNotificaitonInfo(count, ids); 
      return Promise.resolve(memberPayload); 
    }); 
}); 
return trans 
} 

Và cuối cùng, chức năng sendPushNotification giao tiếp với FCM và gửi tải trọng xuống và dọn sạch mã thông báo thiết bị xấu:

async function sendPushNotification(memberID: string, deviceIDs: string[], payload: any, options: any) { 
if (typeof deviceIDs === 'undefined') { 
    console.log("member does not have deviceToken"); 
    return Promise.resolve(); 
} 

const response = await admin.messaging().sendToDevice(deviceIDs, payload, options); 
const tokensToRemove = []; 
response.results.forEach((result, index) => { 
    const error = result.error; 
    const success = result.messageId; 
    if (success) { 
     console.log("success messageID:", success); 
     return 
    } 
    if (error) { 
     const failureDeviceID = deviceIDs[index]; 
     console.error(`error with ID: ${failureDeviceID}`, error); 

     if (error.code === 'messaging/invalid-registration-token' || 
      error.code === 'messaging/registration-token-not-registered') { 
      const doc = admin.firestore().doc(`member/${memberID}`); 
      tokensToRemove.push(doc.update({ 
       deviceToken: { 
        failureDeviceID: FieldValue.delete() 
       } 
      })); 
     } 
    } 
}); 

return Promise.all(tokensToRemove); 
} 

Tôi sẽ đánh giá cao một số trợ giúp về việc thắt chặt bản đánh chữ này :)

Trả lời

0

Rất có thể, có một số chức năng mà bạn đang gọi trên api firebase phải là await ed, nhưng không phải. Tôi không quen với firebase để cho bạn biết chính xác nó là cái gì, nhưng có vẻ như bất kỳ lệnh gọi nào đến API firebase đều có khả năng là await.

Đây là nơi đảm bảo bạn đã cài đặt định nghĩa kiểu cho firebase và sử dụng trình chỉnh sửa tốt. Hãy xem tất cả cuộc gọi firebase của bạn và đảm bảo không ai trong số họ đang bí mật trả lời lời hứa.

Ngoài ra, bạn nên đảm bảo rằng tất cả các chức năng và biến của bạn được nhập mạnh nhất có thể, vì điều này sẽ giúp bạn tránh mọi sự cố.

Vì vậy, những dòng sau trông đáng ngờ với tôi:

fs.doc(`member/${memberID}`); 

transaction.update(docRef, {badgeCount: ++count}); 

const doc = admin.firestore().doc(`member/${memberID}`); 
0

Điều này là do bạn đang mở quá nhiều kết nối http để gửi thông báo đẩy, lý tưởng bạn nên tạo lô 5,10 .. để gửi push .

hãy thử thay đổi,

return await Promise.all(ids.map(async (id) => { ... }); 

đến,

while(ids.length) { 
    var batch = ids.splice(0, ids.length >= 5 ? 5 : ids.length); 
    await Promise.all(batch.map(async (id) => { ... }); 
}