1

I am using a node npm module in a next js app to get data from an api.

static async getInitialProps() {
    const zxapi = new Zxapi(connectId, secretKey);
    const res2 = await zxapi.programs({ region: "DE" }, function(err, result) {
        if (err != null) {
            return err
        }
        console.log(result, "before return");
        return result
        console.log(result, "after return");
    });
    return { res2 };
}

I need to return the values of res2. The "before return" console.log logs the data to the terminal and terminates there. What am I doing wrong? Thanks

brc-dd
  • 10,788
  • 3
  • 47
  • 67
Kofi
  • 9
  • 2
  • can you ```console.log(res2)``` just before ```return { res2 };``` and see if it gets there? – ifiok Jul 16 '17 at 07:28
  • `return result` is probably returning the data. – Abdullah Khan Jul 16 '17 at 07:39
  • @ifiok nope, it doesnt – Kofi Jul 16 '17 at 07:45
  • @AbdullahKhan its not :( iv checked – Kofi Jul 16 '17 at 07:47
  • 3
    `await` only works with functions that return a promise. It does not appear that `zxapi.programs()` returns a promise (because you're using a plain callback with it, not a promise). For a discussion of the options for returning values form an asynchronous function, see this very popular answer: https://stackoverflow.com/a/14220323/816620 – jfriend00 Jul 16 '17 at 09:05
  • possible duplicate of [How do I convert an existing callback API to promises?](https://stackoverflow.com/q/22519784/1048572) – Bergi Jul 16 '17 at 09:39

1 Answers1

3

Can you check if zxapi.programs returns a Promise? If it doesn't, you might have to create a function that makes it return a Promise.

For example, you can use something like

function zxpromise() {
    return new Promise((resolve, reject) => zxapi.programs({ region: "DE" }, function(err, result) {
        if (err != null) {
            reject(err);
        }
        console.log(result, "before return");
        resolve(result);
        console.log(result, "after return");
    }));
}

and then, you can call zxpromise as

const res2 = await zxpromise()
nisargthakkar
  • 43
  • 1
  • 5