0

Can anyone please advise:

I have written a client side webpage which has a Websocket connection to a server side node app. All works fine.

When a certain message is sent through the websocket form the client I get the server to respond (again through the Websocket connection) with some text and I display that on the client side when the reposnse is received. All works fine.

Now, what if I want to make the function on the server an asynchronous one, which waits 4 seconds before returning the string. I can't get that to work, the string is returning as "[object Promise]".

So, the original synchronous code on the server,which is executed in reposnse to the client calling and is working is:

Chatterer.prototype.HandleASCIIMessage = function(szMessage, ws)
{
    ws.send("BANG");
}

Now I have replaced this by with:

Chatterer.prototype.HandleASCIIMessage = function (szMessage, ws)
{
    var sz = this.Test();
    ws.send(sz);
}

Where Test is:

Chatterer.prototype.Test = function()
{
    return this.ShowResult();
}

And the remainder of the code is:

Chatterer.prototype.ShowResult = async function ()
{
    var result = await this.GetAsync();

    return result;
}

Chatterer.prototype.GetAsync = async function ()
{
    var result = await this.AsyncFunc();

    return result;
}

Chatterer.prototype.AsyncFunc = async function ()
{
    return new Promise(resolve => {
        setTimeout(() => {
            resolve("BANG");
        }, 4000);
    });
}

I am trying to not have the ws.send(sz) line called until the 4 seconds is up.

Thanks, Mitch.

1 Answer 1

1
Chatterer.prototype.ShowResult = async function ()
{
    var result = await this.GetAsync();

    return result;
}

The above function returns a promise (an async function returns a promise). This means that the following returns a promise too:

Chatterer.prototype.Test = function()
{
    return this.ShowResult();
}

You could make the above async as well to make it more obvious, yet it's not technically needed.

This means that here:

Chatterer.prototype.HandleASCIIMessage = function (szMessage, ws)
{
    var sz = this.Test();
    ws.send(sz);
}

sz is a promise, so either make HandleASCIIMessage async and var sz = await this.Test();, or use the vanilla Promise API with this.Test().then(sz => ws.send(sz)).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.