Assumptions:
async
causes it's operand to become a Promise, it will [[call]] the operand if it is define, and start a generator if that is the result.await
acts like a yield that performs Promise.cast(operand)
- await will resume (.next the generator) when the promise resolves
- this would allow an
async function*
to queue async tasks while keeping a linear codebase
What brought this up:
async function* doLogin(req) {
try {
var session = await login(req); // wait until the promise resolves
gotoProfile(session);
}
catch (e) {
printError(e);
gotoLogin();
}
// implicit return undefined
}
// usage
doLogin(req).then(...);
You can think of it in Promises and Generators as similar to:
function doLogin(req) {
return new Promise(function (f, r) {
var gen = doLogin_(req);
gen.next();
function doLogin_*(req) {
try {
login(req).then(function (session) {
gen.next(session);
})
.catch(function (e) {gen.throw(e);});
try {
var session = yield; // waiting on our promise to finish...
gotoProfile(session);
}
catch (e) {
printError(e);
gotoLogin();
}
f();
}
catch (e) {r(e);}
}
});
}
doLogin(req).then(end).catch(die); // handle this as a promise
Allan's simplification by use of new
, keeps gen in doLogin_'s scope
function doLogin(req) {
return new Promise(function (f, r) {
new doLogin_(req).next();
function doLogin_*(req) {
var gen = this;
try {
login(req).then(function (session) {
gen.next(session);
})
.catch(function (e) {gen.throw(e);});
try {
var session = yield; // waiting on our promise to finish...
gotoProfile(session);
}
catch (e) {
printError(e);
gotoLogin();
}
f();
}
catch (e) {r(e);}
}
});
}
doLogin(req).then(end).catch(die); // handle this as a promise
Brendan's suggestion to use a library (task.js) - more as a representation of what can be done for simplicity, the library code won't match nicely with source maps / forces having more in the namespace / loading the lib.
spawn(function*() {
try {
var session = yieldlogin(req); // wait until the promise resolves
gotoProfile(session);
}
catch (e) {
printError(e);
gotoLogin();
}
// implicit return undefined
});
Bluebird's
Promise.coroutine