Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass arguments to a promise?

In the examples I see, the code in a promise is static. An example:

var promise = new Promise(function (resolve,reject) {
  if (true)
    resolve("It is a success!")
  else
    reject(("It is a failure."));
});

promise.then(function (x) {
   alert(x);
}).catch(function (err) {
      alert("Error: " + err);
    });

How do I pass arguments to the promise so that useful work can be done? Is it by the use of global variables?

like image 660
Old Geezer Avatar asked Sep 13 '25 03:09

Old Geezer


1 Answers

Usually it may be done with the following code:

function getSomePromise(myVar) {
  var promise = new Promise(function (resolve,reject) {
    if (myVar)
      resolve("It is a success!")
    else
      reject(("It is a failure."));
  });
  return promise;
}

var variableToPass = true;
getSomePromise(variableToPass).then(function (x) {
  alert(x);
}).catch(function (err) {
  alert("Error: " + err);
});

Update:

As @AlonEitan suggested, you can simplify getSomePromise function:

function getSomePromise(myVar) {
  return new Promise(function (resolve,reject) {
    if (myVar)
      resolve("It is a success!")
    else
      reject(("It is a failure."));
  });
}
like image 148
Oleg Avatar answered Sep 14 '25 17:09

Oleg