0

I'm having slight issues with promises in typescript where the results is always pending, even though it's been fulfilled.

I have this function in a utils folder that processes endpoints from another file, which all run on promises

utils folder function

export const GetData = async (
    xx: string[],
    endpointOne: boolean,
) => {
    if (endpointOne) {
        return getDataFromEndpointOne(xx)
    } 

    return getDataFromEndpointTwo(xx)
}

example of endpoint

const getDataFromEndpointOne = (
    xx: string[],
): Promise<any> =>
    Request(
        `/endpoint1/${xx}`,
    );

But in the main folder that's calling the utils folder function, it always (always) returns pending no matter what I try

const data =
    getData(
        ["1", "3", "56"],
        true
    ).then(result => { return result })
  • What's `Request`? – Andreas Sep 11 '21 at 11:07
  • Sorry, my own wrapper around axios – fellinlovewithaman Sep 11 '21 at 11:08
  • `data` will be the promise returned by `then`. You can't *synchronously* get a value that is only provided *asynchronously*. You need to use the data in the `then` callback. (Side note: `.then(x => { return x; })` is pointless.) – T.J. Crowder Sep 11 '21 at 11:09
  • If the code where `const data =` is located at the top level of a JavaScript (ESM) module, and your environment supports [top-level `await`](https://github.com/tc39/proposal-top-level-await) [all modern browsers and most modern bundlers do], you could so `const data = await getData(/*...*/);` Note that it delays loading of your module until the promise returned by `getData` settles. – T.J. Crowder Sep 11 '21 at 11:11
  • Side note: If you don't use `await` in a function, there's no real reason for it to be marked `async`. Your `getData`, for instance, doesn't need `async` (not as shown). – T.J. Crowder Sep 11 '21 at 11:12
  • 1
    ^^^ thank you @T.J.Crowder – fellinlovewithaman Sep 11 '21 at 11:17

0 Answers0