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?
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?
Share Improve this question asked Mar 30, 2017 at 16:04 u936293u936293 16.3k34 gold badges121 silver badges221 bronze badges 6-
1
right now
alert(x)
would alert("It is a success!"), you can change that string to be whatever you want. – Joe Lissner Commented Mar 30, 2017 at 16:07 -
You can pass an object to the
resolve
callback:resolve({status: 'success', message: "It is a success!"})
(For example) and in the resolve callback you can access it likealert(x.message);
oralert(x.status);
– Alon Eitan Commented Mar 30, 2017 at 16:09 - 1 Not global variables, but usually you'll just use any variables in scope at the time the Promise is created. – deceze ♦ Commented Mar 30, 2017 at 16:10
- Just as always, put the value you are creating in a function and let it depend on the parameters?! Your question is the same as "How to pass arguments to a string?" or "How to pass arguments to an object literal?". – Bergi Commented Mar 30, 2017 at 16:20
- What do you consider to be "useful work"? – Bergi Commented Mar 30, 2017 at 16:21
1 Answer
Reset to default 4Usually 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."));
});
}