Home > Blockchain >  Why is the return value of a Promise undefined when the value inside the Promise is defined?
Why is the return value of a Promise undefined when the value inside the Promise is defined?

Time:09-30

In the following code snippet:

1 const GetErrors = async (projectScanID: number, projectName: string) => {
2   try {
3       console.log("fetching errors")
4       const errorsFetch = await fetchErrors(projectScanID);
5       console.log("errorsfetch:", errorsFetch)
6       await setErrors(errorsFetch);
7       console.log("errors", errors)
8       setIsErrorsFetchComplete(true);
9       console.log("errors: ", errors)
10  }
11  catch(e) {
12      enqueueSnackbar(`Could not load errors! Error: ${e}`, {variant: 'error'});
13  }
14}

My console.log on line 5 is displaying that errorsFetch is undefined, despite the Promise in the fetchErrors function I'm calling on that line console.logging the error data on line 6:

1 export const fetchErrors = async (project_scan_id: number): Promise<IError[]> => {
2     let errors = <Array<IError>>[];
3     let string_project_scan_id: string | null = String(project_scan_id)
4     ///fetches error data
5     return Promise.resolve(errors).then(function (value) {
6         console.log("value:", value)
7     }).catch(function (error) {
8         console.log("Error")
9     });
10    }
11}

Notice how I'm using await in the first code snippet to wait for fetchErrors then again to wait for setErrors to finish on line 6 before setIsErrorsFetchComplete(true); on line 8. Why is my constant I'm using to retrieve my return value from fetchErrors undefined on line 5 of the first code snippet?

Edit: errors and isErrorsFetchComplete are states defined in the higher scope before calling GetErrors.

CodePudding user response:

This Promise resolves to a value:

Promise.resolve(errors)

But, you chain onto it here:

.then(function (value) {
  console.log("value:", value)
})

So value in this callback has your errors, but then this doesn't resolve to anything. It essentially "swallows" the resolved value. You can return it from this as well though:

.then(function (value) {
  console.log("value:", value);
  return value;
})

The same is true of the catch callback. If invoked, the resulting Promise chain wouldn't resolve to anything unless that callback function returns something.


The second question doesn't make much sense to me given the code shown. Nothing here is "displaying" anything. And the terminology implies the use of React, which isn't shown here at all either. This probably merits a separate question entirely, once the Promise chaining is sorted out.

  • Related