根据文档在承诺中抛出错误将拒绝它,但事实并非如此

时间:2016-08-11 19:04:02

标签: javascript promise

  

抛出错误也会拒绝承诺

throw new Error(reason);

我试过这里:



const promise = new Promise(function(resolve, reject) {
	var result = 1;

	// This could also be a web request, or anything else either synchronous or asynchronous
	setTimeout(function() {
		result += 10;

		resolve(result);
	},3000);

	document.body.addEventListener("click", function clickHandler() {
		document.body.removeEventListener("click", clickHandler);
        
                // HERE I AM THROWING AN ERROR!
		throw new Error("You clicked");
	});

	document.body.innerText = "Working... Click anywhere to reject the promise with an error.";
});

promise.then(function(value) {
	document.body.innerText = "Everything went fine! The Promise resolved with: " + value;
}).catch(function(error) {
	document.body.innerText = "Something went wrong: " + error;
});

body {
    margin: 0;
    padding: 8px;
    min-height: 100vh;
    box-sizing: border-box;
}




但最终会出现错误,并且解决得很好。

我做错了吗?

1 个答案:

答案 0 :(得分:1)

您没有在承诺的上下文中抛出错误,您在单击处理程序的上下文中发生错误,之后创建承诺。

const promise = new Promise(function(resolve, reject) {

    document.body.addEventListener("click", function clickHandler() {
        // this is not part of the promise and executes sometime later
    });
});

这意味着承诺中的代码(包括侦听器的附件)将在创建承诺时发生,并且当时不会发生错误。

稍后,只要您的click事件触发,您将在完全独立的上下文中异步抛出错误。

const promise = new Promise(function(resolve, reject) {
    // Any error that happens here will result in a promise rejection

    document.body.addEventListener("click", function clickHandler() {
        // Any error that happens here will be thrown within the handler,
        // after the promise was created and resolved
    });
});