我正在尝试了解 Promise 是什么,所以我开始遵循本指南。
我从指南中复制了这段代码,并在我的开发者控制台中进行了尝试:
var promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then…
if (false) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
我收到一条错误消息:
Uncaught (in promise) Error: It broke
。我不明白这是什么意思。谁能解释一下吗?
承诺可以被解决或拒绝。如果是如果/当它被解析时,任何
then
函数都会被调用。如果被拒绝,将调用任何 catch
函数。如果您不提供任何 catch
函数,那么 Promise 可能会有助于打印该警告。
function test(fail) {
return new Promise((resolve, reject) => {
if (fail) {
reject();
} else {
resolve();
}
});
}
// will print rejected 1
test(true)
.then(() => { console.log('resolved 1'); })
.catch(() => { console.log('rejected 1'); })
// might generate the error telling you the promise
// was rejected but you didn't provide a catch function
test(true)
.then(() => { console.log('resolved 2'); })
请注意,该消息是浏览器/JavaScript 引擎发出的有用警告。您不必捕获被拒绝的承诺,但通常您希望这样做,因此该消息很有帮助。
注意 Promise 的工作原理非常重要。当您调用
then(someFunc)
时,它们实际上将 someFunc
放在稍后调用的函数列表中。如果承诺已经履行,他们将调用列表中的每个函数并清除列表。如果承诺没有兑现,他们将什么都不做,直到兑现为止。与 catch
相同,只是它是不同的列表。
这是一个例子
function makePromiseParts() {
let resolve;
let reject;
const promise = new Promise((_resolve, _reject) => {
log('--in promise--');
resolve = _resolve;
reject = _reject;
});
return {
promise,
resolve,
reject,
};
}
function wait() {
return new Promise(resolve => setTimeout(resolve));
}
async function main() {
{
log('--start--');
const p = makePromiseParts();
log('--after make promise--');
p.promise.then(() => { log('then 1'); });
p.promise.then(() => { log('then 2'); });
log('--before resolve--');
p.resolve();
log('--after resolve--');
await wait();
log('--after waiting--');
p.promise.then(() => { log('then 3'); });
p.promise.then(() => { log('then 4'); });
log('--before waiting--');
await wait();
log('--end--');
}
await wait();
log(' ');
{
log('--start--');
const p = makePromiseParts();
log('--after make promise--');
p.promise.catch(() => { log('catch 1'); });
p.promise.catch(() => { log('catch 2'); });
log('--before reject--');
p.reject();
log('--after reject--');
await wait();
log('--after waiting--');
p.promise.catch(() => { log('catch 3'); });
p.promise.catch(() => { log('catch 4'); });
log('--before waiting--');
await wait();
log('--end--');
}
}
main();
function log(...args) {
const elem = document.createElement('pre');
elem.textContent = [...args].join(' ');
document.body.appendChild(elem);
}
pre { margin: 0; }
换句话说,
then
接受一个表示 call this function if and when you're resolved
的函数,而 catch
接受一个表示 call this function if and when you're rejected
的函数。
这意味着你的 Promise 抛出了一个未被捕获的错误。
即你没有按照你的承诺调用 .catch() 。
在你的情况下, if(false) 永远不会评估为 true,所以你的承诺被拒绝。
好线程。我花了很多时间在上面。主要是让我的 .catch 使用正确(而不是“未捕获”)。这是对我有用的最小示例:
<!DOCTYPE html>
<html>
<head>
<title> promise .then .catch </title>
<meta charset="UTF-8">
<script>
"use strict";
let fnresolve, fnreject; // the functions are saved here
let nres=0, nrej=0; // counters
window.onload = async function() {
zlog ('');
while (true) {
let p = new Promise((res, rej) => { fnresolve = res; fnreject=rej; } );
await p
.then( (what) => { nres+=1; zlog(what); } )
.catch((what) => { nrej+=1; zlog(what); } );
}
}
function zlog(msg) {
if (msg!='') document.getElementById('zlog').innerHTML += nres+' resolves, '+nrej+' rejects, this one was '+msg+'<br />';
document.getElementById('zlog').innerHTML += 'push either button<br />';
}
</script>
</head>
<body>
<button onclick='fnresolve("OK");'> RESOLVE </button>
<button onclick='fnreject("NG");''> REJECT </button><br /><br />
<div id='zlog'></div>
</body>
</html>