Reputation: 6192
I want to use a promise with arguments, like the following psudo code:
let lookForXPromise = new Promise(arg1. arg2, function(resolve, reject){
asyncFunc(arg1, arg2, function(value){
if(value != "undefined"){
resolve(value);
}
else{
reject(); // didn't find X
}
});
});
lookForXPromise(1, "foo").then(
function(val){ ... do something...
}).catch(){ ...
But it appears that a promise only receives function(resolve, reject)
, so how can I declare a promise and reuse it with different arguments?
EDIT: this is so it will be possible to iterate over a collection of values and each time send different value to the promise.
Upvotes: 0
Views: 563
Reputation: 40804
A promise is not a function; it is the "promised future return value" of a function. Therefore, you'd just write a function that takes those arguments and creates a new promise:
function lookForXPromise(arg1, arg2) {
return new Promise(function(resolve, reject){
asyncFunc(arg1, arg2, function(value){
if(value != "undefined"){
resolve(value);
}
else{
reject(); // didn't find X
}
});
});
}
// now you can call lookForXPromise as a function:
lookForXPromise(1, "foo")
.then(() => { /* ... */ })
.catch(() => { /* ... */ });
Upvotes: 2