DEV Community

Discussion on: Preventing unhandled promise rejections in async functions

Collapse
 
greim profile image
Greg Reimer • Edited

Wow, it took me a bit to spot the problem before reading the rest of the post! I think there's a deeper problem, which is that createRequest() exposes a dangerous API to users by creating a reference to a promise and storing it implicitly.

const activeRequestHandler = createRequest(requestDefinition);
// activeRequestHandler.response is a promise that's
// now just hanging around, unhandled.

Anyone else using the API will have to be cognizant and use the same workaround. As an alternative, I like how the fetch API does things.

// creates and immediately handles a promise
const resp = await fetch(...);

// ...other logic runs here...

// creates and immediately handles a promise
const content = await resp.text();

Maybe createRequest() should change its API?

const activeRequestHandler = createRequest(requestDefinition);

console.log(typeof activeRequestHandler.response); // function

// other sync/async logic here...

await activeRequestHandler.response();
Collapse
 
gajus profile image
Gajus Kuizinas

For what it is worth, createRequest is just a light abstraction around got. It is got that uses a cancellable promise to implement cancel (/abort) functionality.

I do like your suggestion, though and I think it would be an improvement to got API. Please raise an issue with got. I am sure Sindre will appreciate the suggestion.