In the examples I see, the code in a promise is static. An example:
在我看到的示例中,promise中的代码是静态的。一个例子:
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?
如何将参数传递给promise以便可以完成有用的工作?是通过使用全局变量?
1 个解决方案
#1
2
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:
正如@AlonEitan建议的那样,您可以简化getSomePromise功能:
function getSomePromise(myVar) {
return new Promise(function (resolve,reject) {
if (myVar)
resolve("It is a success!")
else
reject(("It is a failure."));
});
}
#1
2
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:
正如@AlonEitan建议的那样,您可以简化getSomePromise功能:
function getSomePromise(myVar) {
return new Promise(function (resolve,reject) {
if (myVar)
resolve("It is a success!")
else
reject(("It is a failure."));
});
}