出现了一个错误“Uncaught(in promise)stop!!”还有字符串“停下!!”不会被添加到div中
通过在中引入独立的异步函数,您打破了承诺链
.then()
处理程序(抛出,但没有
.catch()
这最终会导致你看到的错误)。
相反,让整个
.然后()
处理程序异步:
function tunggu(waktu) {
return new Promise((resolve) => {
setTimeout((() => resolve(`${waktu.toString()} milisecond has passed`)), waktu);
})
}
const div = document.querySelector('#asd');
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(async (json) => {
console.log(json);
div.innerHTML = 'start<br/>';
const a = await tunggu(2000);
div.innerHTML += a + '<br/>';
throw('stop!!');
const b = await tunggu(3000);
div.innerHTML += b;
})
.catch(error => {
console.log('error occurred', error)
div.innerHTML += error
})
<div id="asd"></div>
或者,从异步IILife中返回承诺,以保持承诺链完好无损:
function tunggu(waktu) {
return new Promise((resolve) => {
setTimeout((() => resolve(`${waktu.toString()} milisecond has passed`)), waktu);
})
}
const div = document.querySelector('#asd');
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => {
console.log(json);
return (async () => {
div.innerHTML = 'start<br/>';
const a = await tunggu(2000);
div.innerHTML += a + '<br/>';
throw('stop!!');
const b = await tunggu(3000);
div.innerHTML += b;
})();
})
.catch(error => {
console.log('error occurred', error)
div.innerHTML += error
})
<div id=“asd”></部门>