私はtry catch文を使用しています。私のtryステートメントでは、try catch文の外で定義された関数から得た値だけを返したい。ただし、値は未定義です。try catchで未定義の値
私は以下のコードを追加してい:
const request = User.friendRequest(userId, friendId, (err, friendshipRequest) => {
if (err) throw err;
return friendshipRequest;
});
を、私は、コールバック関数内(friendshipRequestを)にconsole.log場合は、すべてが魔法のように動作し、私は私が欲しかったJSONオブジェクトを取得します。しかし、try catch文でconst request
を使用しようとすると、const request
は未定義になります。すべてが期待どおりに動作しますが、それでも私は唯一の関数から値を渡すしたい - 私はこれに私のコードを変更し、郵便配達を投稿しているとき
try {
return res.status(201).json({
error: false,
request,
});
} catch (e) {
return res.status(400).json({ error: true, message: e.errsmg });
}
完全なコードは、この
export const sendFriendRequest = async (req, res) => {
const { userId, friendId } = req.params;
const request = await User.friendRequest(userId, friendId, (err, friendshipRequest) => {
if (err) throw err;
return friendshipRequest;
});
try {
return res.status(201).json({
error: false,
request,
});
} catch (e) {
return res.status(400).json({ error: true, message: e.errsmg });
}
};
'あなたがそれにコールバックを渡すときUser.friendRequest'は約束を返すように表示されません。 – Bergi
[try catchで未定義の値が重複する可能性があります](http://stackoverflow.com/q/43836415/1048572) – Bergi