简体   繁体   中英

Typescript Async/Await with SignalR Function

I have encountered a problem where a sequence of SignalR hub function fails to be executed asynchronously.

I have:

//Hub functions
//Initializing hub server and clients.
function HubStart() {
    $.connection.hub.start().then(function () {
        console.log(1);
        return new Promise(resolve => resolve);
    });
}
//Hub server-side function that add user's name to chat board.
function HubUserOnline(user: any) {
    $.connection.boardHub.server.userOnline(user).then(resolve => { return new Promise(resolve => resolve); });
}

//Main
var viewModel = ko.mapping.fromJS(model, mappingOption);
main();

//Definition of the main function
async function main() {
    console.log(0);
    await HubStart();
    console.log(2);
    await HubUserOnline(ko.mapping.toJS(viewModel.CurrentUser))
    console.log(3);
    }
});

However, the console says:

> 0
> 2
> Uncaught (in promise) Error: SignalR: Connection must be started before data can be sent. Call .start() before .send()
>   at hubConnection.fn.init.send (jquery.signalR-2.2.1.js:780)
>   at init.invoke (jquery.signalR-2.2.1.js:2734)
>   at Object.userOnline (hubs:120)
>   at HubUserOnline (WaitingRoom.ts:190)
>   at WaitingRoom.ts:203
>   at Generator.next (<anonymous>)
>   at fulfilled (WaitingRoom.ts:1)
> 1

Thus it indicates the second hub function was going to be executed before the hub instance had been created and it got an error.

The hub functions return JQueryPromise so I tried to let a function return a promise when the hub functions are completed. Can anybody indicate a fault in my code and trial?

I believe the problem is that HubStart and HubUserOnline are not returning a promise and instead you fell in a promise antipattern.

Try the following:

//Hub functions
//Initializing hub server and clients.
function HubStart() {
  return new Promise((resolve, reject) => {
    $.connection.hub.start().then(() => {
      console.log(1);
      resolve();
    });
  });
}
//Hub server-side function that add user's name to chat board.
function HubUserOnline(user: any) {
  return new Promise((resolve, reject) => {
    $.connection.boardHub.server.userOnline(user).then(() => {
      resolve();
    });
  });
}

//Main
var viewModel = ko.mapping.fromJS(model, mappingOption);
main();

//Definition of the main function
async function main() {
  console.log(0);
  await HubStart();
  console.log(2);
  await HubUserOnline(ko.mapping.toJS(viewModel.CurrentUser))
  console.log(3);
}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM