G
G
gunner172019-04-06 00:42:33
Functional programming
gunner17, 2019-04-06 00:42:33

Async await with a generator?

Help create your own implementation of the async await syntax using Promises and generator functions. If using the standard syntax looks like this:

async function fetchData (id) {
    let user = await fetchUser(id),
        friends = await fetchFriends(id);
    return {
        user,
        friends
    };
}

then your own solution should look like this:
let fetchData = _async(function* (id) {
    let user = (yield fetchUser(id)),
        friends = (yield fetchFriends(id));
    return {
        user,
        friends
    };
});

The challenge is to write an _async function that takes a generator function as an argument and returns a new function that will in turn take control of the iterator and return a Promise with the end result.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stockholm Syndrome, 2019-04-06
@StockholmSyndrome

everything is already written

G
grinat, 2019-04-06
@grinat

function _async (generator, prev) {
if (!generator.next) {
generator = generator()
}
const itRes = generator.next(prev)
return itRes.done ? itRes.value : itRes.value.then(r => _async(generator, r), e => generator.throw(e))
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question