0

I have function which run under promise and I want to start another function promise resolved. But I could not do that. Below is my promise function

var promise1
  $(document).ready(function() {
    promise1 = new Promise(function(resolve, reject) {
     getData(url).then(function(data) {
       // do something
     })
    })
  })

Now on the same page different web part we want another function run but only after finish of above function

  $(document).ready(function() {
promise1.then(function(d) {
      var commentURL ="https://xxxx"
      loadComments(commentURL)
    })
})

but second function never runs, please help me

Milind
  • 1,855
  • 5
  • 30
  • 71

2 Answers2

0

I suspect if you gave us a more complete picture of your overall structure, we could suggest a way of doing what you're doing that would be more appropriate.

But answering your actual question: You'd have to create the promise immediately, rather than in a ready callback, but resolve it in the ready callback.

If you have to wait for ready before calling getData, then this is one of the rare situations where it makes sense to use new Promise even though you already get a promise from getData (because of the time delay, you need a promise immediately, but you want to wait to call getData):

var promise1 = new Promise(function(resolve, reject) {
  $(document).ready(function() {
     getData(url).then(resolve).catch(reject);
  });
});

But, unless you really have to wait for ready to call getData, don't (it doesn't immediately make sense to wait to get some data until the page's DOM is complete):

var promise1 = getData(url);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Don't create a promise with new Promise when you already get a promise from a function call, like is your case with getData. Wrapping that in a new Promise callback is known as the Promise constructor antipattern. Try to avoid it.

Do it like this:

var promise1;
$(document).ready(function() {
    promise1 = getData(url).then(function(data) {
        // If you want to pass something on to the next `then`, then return it here:
        return someData;
    });
});

The other part can stay like you had it:

$(document).ready(function() {
     promise1.then(function(d) {
        var commentURL ="https://xxxx"
        loadComments(commentURL)
    });
});

This can only work if promise1 has been initialised by the first code block. If for some reason the code blocks are executed in reversed order and you cannot change this order, then wrap a resolving promise in the second code block, like this:

$(document).ready(function() {
     Promise.resolve().then(function () {
         return promise1;
     }).then(function(d) {
         var commentURL ="https://xxxx"
         loadComments(commentURL)
     });
});
trincot
  • 317,000
  • 35
  • 244
  • 286