let promise = new Promise(function(resolve, reject) {
setTimeout(() => reject(new Error("Whoops!")), 1000);
});
// reject runs the second function in .then
promise.then(
result => alert(result), // doesn't run
error => alert(error) // shows "Error: Whoops!" after 1 second
);
let promise = new Promise(function(resolve, reject) {
setTimeout(() => reject(new Error("Whoops!")), 1000);
});
// reject runs the second function in .then
promise.then(
result => alert(result), // doesn't run
error => alert(error) // shows "Error: Whoops!" after 1 second
);
In the above code snippets even though I am calling reject but promise state is ing as resolved but when I am removing error => alert(error)
from promise.then
then I am getting promise state as rejected
If one is calling reject then promise state should be rejected not resolved am I correct?
4 Answers
Reset to default 2The promise that is resolved is not the original promise, but the promise returned by then
. The original promise is indeed rejected, and you can verify that by console.log(promise)
. But because you chained then
it returns another promise ..
Return value [of
then
]A
Promise
in the pending status. The handler function (onFulfilled
oronRejected
) then gets called asynchronously (as soon as the stack is empty). After the invocation of the handler function, if the handler function:
- returns a value, the promise returned by
then
gets resolved with the returned value as its value;- doesn't return anything, the promise returned by
then
gets resolved with anundefined
value;- throws an error, the promise returned by then gets rejected with the thrown error as its value;
...
This second point is what applies to your case. You can verify that by observing that
Promise.reject().then(undefined, ()=>{})
returns a promise that gets resolved with an undefined
value.
You can also handle Promises in "then-catch" fashion like below
let promise = new Promise(function(resolve, reject) {
setTimeout(() => reject('Error'));
});
promise
.then(result => console.log('Result ', result))
.catch(error => console.log('This is Error message -', error))
The final status of the promise is also rejected in your case. Try console.log(promise); It has nothing to do with error => alert(error)
The code you posted seems to work correctly both on Chrome and Firefox - the Promise was rejected as expected. reject
function marks the Promise as rejected - you can then react upon that rejection either by passing a callback function into a second argument of then
or by using the catch
method. Both approaches are correct.
If you are encountering any unexpected behaviour, verify that you are not using some faulty polyfill that replaces the original Promise
object.
Reference: Promise.prototype.then, Promise.prototype.catch
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745385786a4625432.html
评论列表(0条)