Replace `new Promise` and `.then` with async/await
Closed this issue · 5 comments
We no longer support node 8 so there is nothing holding us back from asyncing and awaiting.
To do this
- Search in files for
new Promise
or.then
. - Replace it with an async function.
- Make a PR.
It is worth keeping the PR's small (maybe only adding a one or two async/awaits at a time) so we can review them quickly and get them merged!
Hi, I'd like to contribute!
Hi! Go for it!
I haven't worked with .then()
blocks in a return statements a lot, it would be awesome if you could help me out here! I'm looking at this bit of code:
return Parser.extractExposedPossiblyTests(filePath).then(
(possiblyTests) => ({
moduleName,
possiblyTests,
})
);
I don't understand how to return a Promise.then()
, using await
, what I could think of is this
possiblyTests = await Parser.extractExposedPossiblyTests(filePath)
return (possiblyTests) => ({
moduleName,
possiblyTests,
})
This will simply wait for the Promise
to resolve and return the function that follows. But I'm assuming we have to return the Promise
as it is and let the code that called this function that called it handle the waiting, or am I wrong?
So the trick it to make the function async so
function xxx(args) {
...
return Parser.extractExposedPossiblyTests(filePath).then(
(possiblyTests) => ({
moduleName,
possiblyTests,
})
);
}
becomes
async function xxx(args) {
...
const possiblyTests = await Parser.extractExposedPossiblyTests(filePath);
return {
moduleName,
possiblyTests,
};
}
and because it is an async function it will return a promise exactly the same as before.
So the trick it to make the function async
Yes! That's given, as the await
is only valid when the function is async
, I wanted to know if we are return
-ing resolved promises or not. Thanks this helps, I'll make some PRs in the morning :)