0

I am trying to write a promise in such a way that I can pass some parameters. Inside, this promise will call a Fetch. This is the code I wrote so far:

const myFunction = (parA, parB, parC) => {
    return new Promise ((resolve, reject) => {
        url = ... // calculated based on the parameters passed above;
        fetch(url)
        .then(response => {
            var object = response.json();
            resolve(object);// the idea is that 'object' is returned by the outmost promise
            console.log('Check');// So far OK, this is correctly printed to the console
        })
        .catch(err => {
            console.log('Error: ' + err);
            reject(err);
        });
//      resolve('1') // Used for test only. With this, everything works, but "object" here is undefined -- I guess it gets executed too early, before the completion of the Fetch
    });

and this is where the promise is called

    myFunction(a, b, c).then(res => {
        console.log('OK');// just testing 
        console.log(res);// just testing 
    });

What happens is that the Fetch resolves OK, but my overall promise doesn't. The last two console.log instructions are never executed.

In short, my problem is: how can I resolve my promise returning the result from the Fetch? It's a promise inside a promise, I guess I could chain them with .then, but I also want to be able to pass parameters.

I also guess I could rewrite the code avoiding this promise chaining, but since I'm also doing it as a way of learning, I prefer to try to figure out first how to solve this problem with this structure.

p.s.: at the moment I am stuck with the promises, cannot use async/await because I am with an old version of node.js and cannot update it

Bob-it
  • 87
  • 1
  • 8
  • what parameter are you trying to pass? an example maybe – HW Siew Jun 23 '20 at 15:41
  • 2
    Please avoid the [explicit Promise constructor antipattern](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it). It's completely unnecessary here, since `fetch` already returns a promise. It's a lot easier to read it if you remove the `new Promise`. I suspect it's probably related to your problem, as well, as you're probably not handling the promise correctly. – VLAZ Jun 23 '20 at 15:42
  • Append a `.catch(console.error)` to your `myFunction(a, b, c).then(res => {…})` chain. – Bergi Jun 23 '20 at 15:58
  • 1
    You cannot pass parameters to a promise. You can pass them to a function (which might return a promise), and that's what your code does just fine. – Bergi Jun 23 '20 at 15:59
  • Thanks to all. The parameters are just strings and date, shouldn't be relevant. @Bergi, if the code is fine, how is that it doesn't work? How can I resolve myPromise (because at the moment it seems to me it never happens)? – Bob-it Jun 23 '20 at 16:06
  • 1
    Maybe the [`response.json()` promise](https://stackoverflow.com/q/37555031/1048572) rejects? – Bergi Jun 23 '20 at 16:15

1 Answers1

1

As @VLAZ already mentioned, it's not necessary to create your own promise here, since fetch() itself already returns a promise. Therefore, you could try this:

const myFunction = (parA, parB, parC) => {
    const url = ... // calculated based on the parameters passed above;
    return fetch(url)
        .then(response => response.json())
        .then(object => {
            console.log('Check', object);
            return object;
        })
        .catch(err => {
            console.log('Error: ' + err);
        });
};
Benjamin Eckardt
  • 709
  • 6
  • 10
  • Thanks @benjamin-eckardt, this seems to be working, exactly the type of solution I was looking for! – Bob-it Jun 23 '20 at 16:12