我想让异步函数像在 1 秒后执行 promise1,然后在 0.5 秒后传递 promise1,然后执行 promise2。我试过这个,但它不起作用。但该功能在放入resolve()
. 我知道这是如何工作的,但我仍然不确定它为什么有效。
const button = document.getElementById('button');
function painting() {
return new Promise ((res) => {
setTimeout(() => {
button.style.backgroundColor = 'green';
res();
}, 1000);
})
.then(() => turnOff());
}
function turnOff() {
return new Promise(() => {
setTimeout(() => {
button.style.backgroundColor = 'red'
}, 500)
})
}
async function startPaint() {
return await painting()
}
button.onclick = function() {startPaint()};
<button id='button' >
hello
</button>
下面的代码是不起作用的:
const button = document.getElementById('button');
function painting() {
return new Promise ((res) => {
setTimeout(() => {
button.style.backgroundColor = 'green';
//res();
//Chaining doesn't happen without res();
}, 1000);
})
.then(() => turnOff());
}
function turnOff() {
return new Promise(() => {
setTimeout(() => {
button.style.backgroundColor = 'red'
}, 500)
})
}
async function startPaint() {
return await painting();
}
button.onclick = function() {startPaint()};
<button id='button' >
hello
</button>
你创建了一个新的承诺,但你永远不会解决它。您需要res()
在setTimeout()
. 您手动创建的新承诺永远不会解析,直到您从承诺构造函数内部的某处调用解析函数。这就是 promise 构造函数的工作原理。
new Promise((resolve, reject) => {
// you must call resolve(someVal) or reject(someErr) inside this function
// somewhere or the promise will never resolve or reject
// for example
setTimeout(() => {
resolve("hello");
}, 1000);
// nothing happens automatically when this function finishes execution
}).then(val => {
console.log(val);
}).catch(err => {
console.log(err);
});
而且,如果您的承诺从未被解决或拒绝,则永远不会调用.then()
或.catch()
处理程序。承诺将永远处于“待定”状态。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句