我正在使用包“fcm-node”來向某些設備 ID 發送通知。
sendNotification 函式如下:
const FCM = require('fcm-node');
const serverKey = process.env.SERVER_KEY;
const fcm = new FCM(serverKey);
function sendNotification(registrationToken, title, body, type, key) {
const message = {
to: registrationToken,
collapse_key: key,
notification: {
title: title,
body: body,
delivery_receipt_requested: true,
sound: `ping.aiff`
},
data: {
type: type,
my_key: key,
}
};
fcm.send(message, function (err, value) {
if (err) {
console.log(err);
return false;
} else {
console.log(value);
return value;
}
});
};
module.exports = {
sendNotification
};
我用來呼叫這個函式的api函式如下:
router.get('/test', async (req, res, next) => {
const promise = new Promise((resolve, reject) => {
let data = sendNotification('', 'dfsa', 'asds', 'dfas', 'afsdf');
console.log(data)
if (data == false) reject(data);
else resolve(data);
});
promise
.then((data) => { return res.status(200).send(data); })
.catch((data) => { return res.status(500).send(data) })
});
當我 console.log 來自 sendNotification 的“err”和“value”時,我得到以下任一資訊:
{"multicast_id":4488027446433525506,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1652082785265643U7c6f39557c6f39"}]};
{"multicast_id":8241007545302148303,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
如果成功,我確保設備正在接收通知。
問題出在api的資料中。它總是“未定義”,無論發送通知是否成功,我都會得到 200 Ok 狀態。
似乎是什么問題?
uj5u.com熱心網友回復:
您不能從function (err, value) {}節點樣式異步函式的回呼中回傳任何內容。
您的sendNotification()函式需要回傳一個承諾。util.promisify()使從節點樣式的異步函式轉換為回傳承諾的異步函式很方便。注意return,這很重要:
const FCM = require('fcm-node');
const serverKey = process.env.SERVER_KEY;
const fcm = new FCM(serverKey);
const { promisify } = require('util');
fcm.sendAsync = promisify(fcm.send);
function sendNotification(registrationToken, title, body, type, key) {
return fcm.sendAsync({
to: registrationToken,
collapse_key: key,
notification: {
title: title,
body: body,
delivery_receipt_requested: true,
sound: `ping.aiff`
},
data: {
type: type,
my_key: key,
}
});
}
module.exports = {
sendNotification
};
現在你可以做你想做的事
router.get('/test', async (req, res, next) => {
try {
const data = await sendNotification('', 'dfsa', 'asds', 'dfas', 'afsdf');
return res.status(200).send(data);
} catch (err) {
return res.status(500).send(err);
}
});
uj5u.com熱心網友回復:
也許它會有所幫助,首先嘗試在 sendNotification 中回傳您的回應(承諾),因為實際上您有一個 void 函式,這就是為什么它總是未定義并且在您的路線之后
router.get('/test', async (req, res, next) => {
try {
const data = sendNotification('', 'dfsa', 'asds', 'dfas', 'afsdf');
if (data) {
return res.status(200).send(data);
}
} catch(err) {
return res.status(500).send(err);
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/471232.html
標籤:javascript 节点.js 打字稿 火力基地 表示
