Skip to content

Instantly share code, notes, and snippets.

@rogerpoon
Created May 9, 2020 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rogerpoon/205d7b2d1d01b07764882817db3f8085 to your computer and use it in GitHub Desktop.
Save rogerpoon/205d7b2d1d01b07764882817db3f8085 to your computer and use it in GitHub Desktop.
// We introduce two new keywords:
// suspend - Creates "suspended" functions, which will make your asynchronous code "synchronous" while keeping your UI responsive
// next - A "return" keyword for suspended functions
// Exhibit A: sleep function, no return value
external setTimeout;
suspend void sleep(int ms) { // use the 'suspend' modifier
setTimeout(void() {
next; // we do not return a value
}, ms);
}
player.moveLeft(5);
sleep(100);
player.moveUp(2);
// Exhibit B: Read a file, return a value
import System;
external require;
external fs = require("fs");
suspend string? readFile(string path) { // use 'suspend' again, but this time with a nullable 'string' return type
fs.readFile(path, void(err, contents) {
if (err) {
Console.error(err);
next null;
}
next contents; // 'next' is a 'return' statement for async code
});
}
string? contents = readFile("/home/foo/bar.txt");
// You can use any error handling mechanism including:
// 1) nullable/existent types
// 2) boolean values
// 3) "out" parameters (a la C)
// 4) result types (e.g. via classes)
// 5) etc.
// Exhibit C: read a file (without nullable types, throw on error)
import System;
external require;
external fs = require("fs");
suspend string readFile(string path) { // return just 'string' instead of nullable 'string?'
fs.readFile(path, void(err, contents) {
if (err) {
throw err; // I'm told by the team that 'throw' will "just work," even from inside callback code
}
next contents;
});
}
string contents = readFile("/home/foo/bar.txt");
Console.trace(contents); // eeeeaaaasy
// Exhibit D: suspend-next is compatible with ECMAScript 6 Promises right out of the box
// JS:
async function foo() {
return 1;
}
// JS++:
external foo;
suspend int wrapFoo() {
foo().then(void(result) { // notice the callback has return type 'void'
next result; // but 'next' applies to the outer 'wrapFoo' int return type
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment