Struggling to get a value from a promise.
When I resolve the promise and console.log the result I see this:
46 38
This is the correct value I expect to see. However, when I call the method that is supposed to return this promise (receives data from a websocket), I get this:
user id is matched_id 1096
This is my code. This is the method that receives data from my websocket:
async sendData(data){
if(this.socketRef.readyState !== WebSocket.OPEN) {
console.log('we are still waiting')
await new Promise((resolve, reject) => {
console.log('now opening websocket')
this.socketRef.addEventListener('open', resolve);
});
}
console.log('now sending', data)
this.socketRef.send(data)
const result = await new Promise((resolve, reject) => {
this.socketRef.onmessage = e => {
resolve(e.data)
}
});
console.log('what is result', result)
return String(result)
This is where this method is triggered:
function receiveWebSocketData(matchedUser, roomId){
const userID = WebSocketInstance.sendData(matchedUser+' '+roomId)
const fulfilled = userID.then((res)=> { return res })
const fulfilledPromise = setTimeout(()=>{
fulfilled.then((result)=> { return result } )
}, 5000)
return fulfilledPromise;
};
When I console.log the result from the above function this is where I receive the 1096 output.
UPDATE I have tried a solution from the answer I have received so far:
async sendData(data){
if(this.socketRef.readyState !== WebSocket.OPEN) {
console.log('we are still waiting')
await new Promise((resolve, reject) => {
console.log('now opening websocket')
this.socketRef.addEventListener('open', resolve);
});
}
console.log('now sending', data)
this.socketRef.send(data)
const result = await new Promise((resolve, reject) => {
this.socketRef.onmessage = e => {
resolve(e.data)
}
});
return String(result)
and
async function receiveWebSocketData(matchedUser, roomId){
return WebSocketInstance.sendData(matchedUser+' '+roomId);
I then tried this console.log(await receiveWebSocketData(matchedUser, roomId)
and get the error:
Unexpected reserved word 'await'.
when I try this:
console.log('what am I getting receiveWeb', receiveWebSocketData(matchedUser, roomId).then((res) => console.log(res)))
I get this:
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: undefined
setTimeoutwhich is the id used forclearTimeout.awaitin this function if you need values here