user10608273
user10608273

Reputation:

JavaScript not delivering promise

I have two functions. function1() takes more time to complete than function2() because it does a fetch request. I need them to be launched in this order, but the results of function2() are the first that are displayed on the HTML DOM. So, I tried to resolve this with promises. I made the first function a variable, and created the following code:

let promise1 = function1() {
  fetch()
   .then(do x)
   .then(display x to HTML DOM)
  return 0;
};

function2(a) {
  // use the a;
  // display some things to the HTML DOM based on `a`
}

promise1.then((a) => {
      function2(a);
    });

Originally, these two functions don't need to interact with one another, but in order to make this work with promises, I created an artificial need by using that return statement. However, this doesn't work: I get a TypeError: promise1.then is not a function error. I skimmed through the 'Learn more' webpage, but those scenarios don't apply here.

I am quite new to JS and a neophyte to promises. Am I missing something?

Upvotes: 0

Views: 70

Answers (2)

Liam
Liam

Reputation: 29760

You just need to return the promise returned from fetch in your first code block:

let promise1 = function1() {
  return fetch()
   .then(do x)
   .then(() => {
        //returns also need to be async
        return 0;
    });

  //don't do this
  // return 0;
  // return inside the then() above
};

function2(a) {
  // use the a;
  // display some things to the HTML DOM based on `a`
}

promise1.then((a) => {
      function2(a);
    });

To explain this in greater detail; Your fetch runs async. So any subsequent functions will not wait (block). fetch returns a Promise that allows you to chain subsequent functions when the async function finishes. So to run anything after fetch you need to consume the Promise that fetch returns. then is a function of the Promise object, not fetch itself, to consume the promise (call then on the promise object) you need to return it first, hence return fetch().... How do I return the response from an asynchronous call? goes into this in detail

Upvotes: 1

Dacre Denny
Dacre Denny

Reputation: 30390

To address this, you will need to ensure function1 returns a promise object.

By returning a promise object, this allows you to "chain" subsequent .then() handlers off of calls to that function (ie promise1) as you are trying to do.

So in the case of your specific problem, you would want to do something like this:

let promise1 = function1() {
    return fetch('/some/url').then(function (response){
        // Do response processing logic here
        return response; 
    }).then(function (data)  {
       //Chain any other data/response processing
       return data;
    });
};

The key thing to remember here is to return the call to fetch, as well as return data in each then handler that you chain to the call to fetch.

Hope that helps!

Upvotes: 1

Related Questions