Getify: Why I'm not waiting on `await`
http://web.archive.org/web/20160613020936/https://blog.getify.com/not-awaiting-1/
async..await
basically a next version of Promises.
A promises version:
function getOrderDetails(orderID) {
return db.find( "orders", orderID )
.then(function(order){
return db.find( "customers", order.customerID )
.then(function(customer){
order.customer = customer;
return order;
});
});
}
getOrderDetails( 1234 )
.then( displayOrder, showError );
Then with async
:
async function getOrderDetails(orderID) {
var order = await db.find( "orders", orderID );
var customer = await db.find( "customers", order.customerID );
order.customer = customer;
return order;
}
getOrderDetails( 1234 )
.then( displayOrder, showError );
The syntax is very similar to the generators
pattern:
function *getOrderDetails(orderID) {
var order = yield db.find( "orders", orderID );
var customer = yield db.find( "customers", order.customerID );
order.customer = customer;
return order;
}
run( getOrderDetails( 1234 ) )
.then( displayOrder, showError );
The difference is that we need to run (run(..)
) the generator function from the "outside", and cannot step over automatically when the yield
ed promise returns.
await
always deals with promises, wrapping a primitive value if necessary