Reputation: 21
What are acceptable arguments when it comes to the resolve() and reject() methods inside a promise object?
I typically see strings and numbers. I assume most other data types in js? i.e. objects, functions, arrays etc.
let x = new
Promise(function(resolve,reject){
resolve("string");
reject("error");
});
Upvotes: 1
Views: 77
Reputation: 707646
resolve()
can be called with any Javascript type. All it does is pass that value straight through to the whoever is listening to the host promise with .then()
or await
.
The one exception is if you resolve it with a "thenable" (anything that behaves like a promise object), then that promise itself will be waited for and the resolved value of the original promise will become the resolved value of that new promise.
In fact, there's no way to directly resolve to a promise itself because resolve()
will detect that you resolved to a promise and will chain to it. If you ever had a reason to do that, you would have to wrap the promise in an object and resolve with the object.
There's nothing stopping you from passing any Javascript value to reject()
either, but it is an often-practiced convention to reject with Error objects and there's a fair amount of error handling code that can be simpler or easier or may even expect you to use Error objects. It also has the advantage of offering you a stack trace (though sometimes a smaller asynchronous stack trace) that will at least tell the caller where the error originated if they need more info about what might have happened. But, there's nothing in the standard or implemented in the language that requires you to reject()
with an error object.
You may also want to note that your example calls resolve("string")
and then calls reject("error")
. A promise is a one-shot device. The first resolve()
or reject()
that gets called is the only one that gets paid any attention to - any subsequent calls to either are simply ignored. A promise "latches" the first resolved value or reject reasons you give it and can never be changed after that.
Upvotes: 2