Josef Holmes
Josef Holmes

Reputation: 161

Issues with placement of Javascript promise

What am I doing wrong with the placement of this promise?

I need all the elements of the first function to complete before the second function gets triggered.

Thanks in advance.

Function 1:

var promise1 = $("#button-1").on('click', async new Promise(function(resolve, reject) {

  csInterface.evalScript("Duplicate()");
  await SafeMode();
  csInterface.evalScript("FlattenImage()");
  await SafeMode();
  csInterface.evalScript("ConverttosRGB()");
  await SafeMode();
  csInterface.evalScript("Resolution300PPI()");
  await SafeMode();
  csInterface.evalScript("SetBackgroundtoLayer()");
  await SafeMode();
  csInterface.evalScript("Postcard1()");
  resolve();
}));

Function 2:

promise1.then(function() {

// next function here

});

Upvotes: 1

Views: 82

Answers (2)

kockburn
kockburn

Reputation: 17626

promise1 is not a promise and is actually a jQuery object. Make a function that will generate the promise you require (see below).

const promise1 =() => new Promise(async function(resolve, reject) {

  /** Commented so you can see that it works
  csInterface.evalScript("Duplicate()");
  await SafeMode();
  csInterface.evalScript("FlattenImage()");
  await SafeMode();
  csInterface.evalScript("ConverttosRGB()");
  await SafeMode();
  csInterface.evalScript("Resolution300PPI()");
  await SafeMode();
  csInterface.evalScript("SetBackgroundtoLayer()");
  await SafeMode();
  csInterface.evalScript("Postcard1()");*/
  
  //Adding time
  setTimeout(()=>{
    console.log("promise1");
    resolve();
  }, 500);
  
})

$("#button-1").on('click', () => {
  promise1().then(() => {
    //next bit of your code here
    console.log("next");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button-1">Click me</button>

Upvotes: 3

ESN
ESN

Reputation: 86

on() function will not return a promise, you need to declare your async function before, call it in as your callback and chain it with your THEN.

Also, async function will automatically return a Promise, no need to built it yourself.

const resolveAfter1Seconds = function(id) {
  return new Promise(resolve => {
    setTimeout(function() {
      resolve("resolution " + id);
    }, 1000);
  });
};

const callback = async function() {

  console.log("in callback", "start");
  
  let res = await resolveAfter1Seconds(1);
  console.log("in callback 1", res);
  res = await resolveAfter1Seconds(2);
  console.log("in callback 2", res);
  res = await resolveAfter1Seconds(3);
  console.log("in callback 3", res);
  
  return "what you want your promise to finally return";
};


$("#button-1").on('click', () => {
  callback().then(x => console.log("THEN", x))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="button-1">Click me!</button>

Upvotes: 1

Related Questions