Issue
I have an async function which I intend to return an object of type MyResponseType. As I understand, an async function must return a Promise, so I created the following:
import mongoose from 'mongoose'
import MyModel from './models/MyModel'
import { MyResponseType } from "../common/types";
const myFunc = async (
title: string,
text?: string
): Promise<MyResponseType> => {
const result = await MyModel.create({
title,
text,
});
return {
message: 'Success',
result
};
};
My questions are:
Is this the right way to return from an
asyncfunction, assuming I want the result in aresolvedstate when the caller callsawait myFunc({...})?Why doesn't typescript complain that the return type is
MyResponseType, even though it is expectingPromise<MyResponseType>? Is there some implicit conversion going on?
Solution
- Is this the right way to return from an
asyncfunction, assuming I want the result in a resolved state when the caller callsawait myFunc({...})?
Yes. (But it's a fulfilled state, not [just] a resolved state. More about promise terminology in my blog post.)
- Why doesn't typescript complain that the return type is
MyResponseType, even though it is expectingPromise<MyResponseType>? Is there some implicit conversion going on?
Not conversion, but yes, something implicit. async functions are syntactic sugar for promise creation and consumption. They always return promises. The value you provide with return ___ is the fulfillment value used to fulfill the implicit promise they create.
In your example, myFunc runs synchronously until after it calls MyModel.create; once it has the promise from create, it passes it to await and the function creates and returns its own promise. Later, asynchronously, when the promise from create is settled, one of two things happens:
If the promise from
createis fulfilled, the logic ofmyFunccontinues and, in this case, fulfills the promise frommyFuncwith the object you provide toreturn.If the promise from
createis rejected, your function's promise is rejected with the rejection reason thecreatepromise provided.
(That's slightly simplified, but the gory details aren't necessary here.)
Answered By - T.J. Crowder
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.