-2

I have this userscript for GreaseMonkey. I created a function (A) which calls an other function (B). I want to wait running the A function further and wait for the B function to return. Function B contains a button, so in fact I want A to wait for the button press.

I tried this with the async and await but that didn't work for me show I now tried to use the .then() option. In the then() I created a function (nextI) to increase the i after running function B.

function A(){
    var i = 0
    while (i < 3){
        var data = jsonResponse[i];
        var x = data.x;
        var y = data.y;
        B(x, y).then(
            nextI(i)
        )
    }
)

function B(x, y){
    // do some stuff
    let button = document.getElementById("button");
    button.addEventListener("click", () => {
        console.log("Button clicked.");
        return
   });
}

function nextI(i){
    return i + 1
}

So I want to pause A until script B is done and I clicked the button.

George
  • 73
  • 4
  • 15

2 Answers2

1

1. Number is passed by value

Thus, giving i to nextI increases a local copy (i.e. the input parameter).

2. B doesn't return Promise

function B(x, y) {
  let button = document.getElementById("button");

  // FIX HERE
  return new Promise(resolve =>
    button.addEventListener("click", () => {
      console.log("Button clicked.");
      resolve('some data')
    })
  )
}

3. Promise#then accepts a function

So, B (nextI (i)) isn't correct, but B(() => nextI (i)).

N. Other issues

There should be other issues there. For example, you're running functions whose return type/value is Promise in a fire&forget way. Take a look at Promise.all or Promise.race.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
0

before using .then(), you first have to return a promise.

function B(x, y){
  return new Promise((resolve, reject) => { 
     // do something here

     let button = document.getElementById("button"); 
     button.addEventListener("click", () => { 
          console.log("Button clicked."); 
          resolve('foo');
     });

  });
}

take a look https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Vinay Sheoran
  • 528
  • 3
  • 15