On Wed, May 25, 2016 at 10:30 PM, Per Hedbor () @ Pike (-) developers forum <10...@lyskom.lysator.liu.se> wrote: >>I think the biggest benefit is that your async programming becomes/or >>looks more sequential/synchroneous which tend to be easier to follow, >>or in other words less spaghetti-ish. > > > And I definitely beg to differ that. > > Take this future-less code from a chat server: > > | void rpc_call_muc_join(ReturnCall x, mapping args ) > | { > | [string muc,string who] = get_args(args, > | "muc",stringp, > | "inviter",ornull(stringp)); > | > | Channel channel = get_destination( muc ); > | int when = now(); > | > | channel->when_available() > | { > | if( !channel->exists() ) > | client_error(x, "No such channel" ); > | > | channel->joined( user->id, when ) { > | me->join_channel( channel ) { > | channel->add_message( msg( "joined", > | "user_ids",({format_destination(me)}), > | "by",format_destination(me), > | "when", now)) { > | x(true); // return true. > | }; > | }; > | }; > | }; > | } > > > Todays quiz: Is it really harder to read, and how many asynchronous levels > do you think there is in it? :)
If you want your asynchronous code to look truly clean, the way synchronous code does, there needs to be a way to have a function pause its execution and let something else carry on. Python can do this, either with generator functions or with the new async/await keywords. Adapting the style to Pike syntax, it'd be something like this: async string talk_to_socket(string msg) { array(string) ips = await resolv("destination.ip.address"); foreach (ips, string ip) { Stdio.File sock = Stdio.File(); sock->open_socket(); if (await sock->connect(ip, 5678)) break; } await sock->write("helo\n"); await sock->write(msg + "\n"); string data = await sock->read(1024, 1); sock->close(); return data; } Whenever you say "await", you trigger a sub-action, and the current call gets suspended. It functions pretty much like cooperative threading; effectively, any 'await' can result in a context switch. Without language support like that, everything's going to be a pile of (probably lambda) functions, one way or another. ChrisA