简体   繁体   中英

How do I neaten up nested callbacks?

I'm using the FB SDK for Unity, and I'm finding it to be cumbersome with lost of callbacks due to async functions that need to be returned in sequence. How do I abstract my code so this is cleaner and seperate my logic / flow from the async callbacks?

My logic is this:

  • If the player is not logged in, log them in (Async)
  • If they are logged in, then check they have the right permissions (Async)
  • If they don't have the right permissions, request them. (Async)
  • Once they have the "post score" permissions, post the score. (Async)

Here's a pseudo example of what I'm trying to do:

Init()
{
 LogInWithCallback(LoginResponse);
}

public LoginResponse(response)
{
   if(response.loggedIn)
   {
      checkPermissions();
   }
}

public checkPermissions(){

   checkPermissionsWithCallback(permissionCheckCallback);
}

public permissionCheckCallback(ResponseDelegate)
{
  //If the player doesn't have the right permissions, request them.

   requestPermissions("score permission",permissionRequestCallback);
 }

 public permissionRequestCallback()
 {
   //if requesting the score permission was successful post score;
   Postscore();  // <- It doesn't make sense to have logic which posts the player's score this deep down a callback chain, but I don't know any other way around.
 }

I've encountered this problem myself a while ago!

Try using promises . It is a programming pattern that is getting very popular in javascript nowadays , but they're also available for C# . Of course, if Unity would catch up with modern C#, we would be able to use things like await , too, but that's something that's not going to happen soon.

On one hand, they're making code much easier and straightforward, but on the other, they often make debugging harder, since instead of readable method names, you get something like m_42345 in crash logs for anonymous delegates.

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