u936293
u936293

Reputation: 16234

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?

Upvotes: 4

Views: 9856

Answers (1)

Oleg
Oleg

Reputation: 23277

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."));
  });
}

Upvotes: 4

Related Questions