0

I have an async function that involves an Await Fetch and does some other logic both before and after. The function must return a string at the end, let's say "success" or"failure".

const uspsVerification = async (addr: string) => {

    //... Additional Logic ...

    await fetch("/service/verify-address",requestOptions)
    .then(res => res.json())
    .then(data => {
        
          // ... Additional logic ...

          if (someCondition1) {
             // Return or resolve: "success"
             return "success";
             // Promise.resolve("success");

          } else if {
             // Return or resolve: "failure"
             return "failure";
             // Promise.resolve("failure");
          }
        
    });
}

Neither option works. First of all, I can't simply assign a result variable to this function call and check it:

var result = uspsVerification(..);
if (result === 'success') { .. }

Error: Type 'Promise<void>' is not assignable to type 'string'.

Also, I can't use return new Promise(function(resolve, reject) { around the function body. If I do, I get the error

const uspsVerification = async (addr: string) => {
    return new Promise(function(resolve, reject) {
        //...
        await fetch("/service/verify-address",requestOptions)
        //...
            resolve(..);
        //...
    });

Error: 'await' expressions are only allowed within async functions and at the top levels of modules.

gene b.
  • 10,512
  • 21
  • 115
  • 227
  • 1
    You forgot to put a `return` statement in `uspsVerification`. You `await` the chain of `fetch.then().then()` and finally return `undefined` – Quentin Aug 22 '23 at 14:52
  • 3
    Why are you using `then()` inside an `async` function? – Quentin Aug 22 '23 at 14:52
  • 3
    Yea don't mix `async` and `await` code with `.then()` callbacks, that's a sure recipe for confusion. The whole point of `await` was to make that mostly unnecessary. – Pointy Aug 22 '23 at 14:54
  • @Quentin What do you mean I "forgot to put in a return"? Do you see these lines: `return "success";``return "failure";` ? – gene b. Aug 22 '23 at 15:15
  • 3
    @geneb. — The arrow function you pass to `then()` is not the `uspsVerification` function. – Quentin Aug 22 '23 at 15:16

0 Answers0