async icon indicating copy to clipboard operation
async copied to clipboard

Improved means to create a `Future` with no existing async context

Open gwynne opened this issue 7 years ago • 0 comments

JavaScript's Promise library provides Promise.try() as a static method primarily for the purpose of folding error handling of "before the async stuff starts" code into the async model, so that the developer doesn't need to handle both sync and async errors:

return Promise.try(() => {
    // do some sync work that could throw an error
    return someSynchronousValue
}).then((value) => {
    // use the value, do some async work
});

or

return Promise.try(() => {
    // do some sync work that could throw an error
    return startAsyncPromise()
}).then((value) => {
    // use the value
});

These cases correspond neatly to Future's map(to:) and flatMap(to:) methods - I propose adding static variations, like so:

return Future.map(to: SomeType.self) {
    return try getSomeSynchronousValue()
}.flatMap(to: SomethingElse.self) {
    return try getSomethingElseAsync($0)
}.map(to: Response.self) {
    return makeResponseWithValue($0)
}

or

return Future.flatMap(to: SomethingElse.self) {
    return try getSomethingElseAsync()
}.map(to: Response.self) {
    return makeResponseWithValue($0)
}

gwynne avatar Dec 19 '17 22:12 gwynne