function goodFun(){
console.log('this is good fun');
}
function badFun(){
console.log('this is bad fun');
}
const promise = new Promise(goodFun , badFun);
console.log(promise); // status , pending
promise.then(); // resolved
console.log(promise); // status , still pending !!! how ???
promise.then(); // running same promise twice
输出:
this is good fun
Promise { <pending> }
Promise { <pending> }
一旦我解决了这个承诺,它仍然表明它正在等待。第二次,它不打印&#34; goodFun&#34;的内容。 ,有人可以帮助我吗,我错过了什么?
更新: 此外, 第一个console.log(promise)的输出是在promise.then()之后?这也令人困惑?为什么会这样?它应首先打印控制台输出然后再打开promise.then()秒。
答案 0 :(得分:1)
尊重,这根本不是你如何使用承诺。我建议您完成一些教程,可能是the MDN one。
一些问题:
Promise
构造函数只接受一个参数。then
无法解决承诺。then
毫无意义。这是你的例子(最好我可以解释它,无论如何)更新为正确使用promises:
const promise = new Promise(function(resolve, reject) {
// Often a promise is used with asynchronous operations, so let's use
// setTimeout to emulate one
setTimeout(function() {
// Let's give the promise a ~2 in 3 chance of resolving, a ~1 in 3 chance of rejecting
if (Math.random() >= 1 / 3) {
console.log("Resolving the promise");
resolve();
} else {
console.log("Rejecting the promise");
reject();
}
}, 100);
});
function goodFun(){
console.log('this is good fun');
// Now it's settled (resolved)
console.log(2, promise);
}
function badFun(){
console.log('this is bad fun');
// Now it's settled (rejected)
console.log(3, promise);
}
promise.then(goodFun, badFun);
// Not settled (resolved or rejected) yet
console.log(1, promise);
You'll have to look in the real console to see the promise internal state, as it's not available to JavaScript code.