0

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
4
  • 1
    You're returning the result of setTimeout which is the id used for clearTimeout. Commented Aug 25, 2022 at 22:26
  • @ChrisHamilton I needed the setTimeout to return the value from a fulfilled promise. I can't seem to get the value out of the promise without the setTimeout Commented Aug 25, 2022 at 22:42
  • You have to await in this function if you need values here Commented Aug 25, 2022 at 22:53
  • 1
    Does this answer your question? How do I return the response from an asynchronous call? Commented Aug 25, 2022 at 22:53

1 Answer 1

0

That's not how promises work. Just return the promise.

function receiveWebSocketData(matchedUser, roomId){
    return WebSocketInstance.sendData(matchedUser+' '+roomId);
};

To access the returned value use await or .then()

console.log(await receiveWebSocketData(matchedUser, roomId));

or

receiveWebSocketData(matchedUser, roomId).then((res) => console.log(res));
Sign up to request clarification or add additional context in comments.

7 Comments

All of these solutions return this: [[Prototype]]: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: undefined When I console.log fulfilled from the function I have this is what I have at that point: [[Prototype]]: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: "46 24"
Here's an example: stackblitz.com/edit/typescript-5aanau?file=index.ts. What you're seeing is probably an issue in your sendData function.
Added an update with my attempt at this solution and what I am receiving
You're misunderstanding, it's impossible for receiveWebSocketData to return the resolved value. Anywhere that wants to use the result needs to use one of the two methods. It looks like you're trying to do console.log(receiveWebSocketData(...)) without using await or .then(). Also, don't add a 3 second delay to your promise, I just did that to simulate an api call. Read my answer again carefully, the changes you showed do not reflect what I wrote.
When I remove the 3 second delay and add await to my console log I get the error Unexpected reserved word 'await'. If I use the then() method within the console log I get this: [Prototype]]: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: undefined
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.