我正在嘗試在我的專案中實作承諾和異步/等待。我需要使用 fetch 將一些資料發布到服務器,然后使用 javascript 執行其他行程。但我對如何處理嵌套 async/await 承諾的錯誤感到困惑。
[編輯-添加了主要問題]
問題是有一個錯誤“未捕獲(承諾)停止!” 和字串“停止!!” 不會被添加到 div 中
這是我嘗試過的:
function tunggu(waktu) {
return new Promise((resolve) => {
const action = setTimeout(() => {
const str = `${waktu.toString()} milisecond has passed<br/>`;
resolve(str);
}, waktu);
})
}
const div = document.querySelector('#asd');
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => {
console.log(json);
(async () => {
div.innerHTML = 'start<br/>';
const a = await tunggu(2000);
div.innerHTML = a;
throw('stop!!'); // it looks like this line is causing the error
const b = await tunggu(3000);
div.innerHTML = b;
})();
})
.catch(error => {
console.log('error occurred', error)
div.innerHTML = error
})
<div id="asd"></div>
這(也在jsfiddle上)只是我的代碼的簡化版本,在我的專案中,fetch 使用方法 POST,而 js 行程實際上有更多的行程,所以我使用throw它,因為錯誤可能發生在任何地方。
uj5u.com熱心網友回復:
出現錯誤“未捕獲(承諾)停止!!” 和字串“停止!!” 沒有被添加到 div
您通過在處理程式中引入一個獨立的異步函式.then()(它會拋出,但沒有.catch()自己的,最終導致您看到的錯誤)打破了承諾鏈。
相反,使整個.then()處理程式異步:
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>
或者,從您的異步 IIFE 回傳承諾,以保持承諾鏈完整:
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"></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/466440.html
