【发布时间】:2019-08-31 02:56:05
【问题描述】:
我创建了一个从我的服务器获取数据的承诺,当有网络连接时它可以完美运行。
我添加了一个 .catch() 以便在服务器不可用时显示一个 DOM 元素。触发时,.catch() 起作用并显示 DOM 元素,但 2 秒后消失。
我尝试在 .catch() 中添加 DOM 元素。我还尝试将 DOM 添加到外部函数中并调用它。我还尝试将外部函数传递给 reject() 函数。没有任何效果。
---样式表---
#notice { width: 100vw; height: 100vh; opacity: 0; animation: fade-in 2s; background-color:white; z-index: 60; display:flex; align-items: center; text-align: center; } #notice h1 { font-size: 10vh; font-family: 'Verdana'; color: black; } #notice * { position: static; }
---Javascript---
getSolvedDeck = () => { let failed = false; new Promise((resolve, reject)=>{ let xhr = new XMLHttpRequest; xhr.open('GET', "https://mrlesbomar.com/solitaire/cgi-bin/get_solved_deck.php"); xhr.onload = () =>{ if (xhr.status >= 200 && xhr.status < 300) { resolve(xhr.response); } else { reject(xhr.statusText); } } xhr.onerror = () => reject(xhr.statusText); xhr.send(); }).then(stuff=>{ console.log('Awesomeness'); }).catch(error=>{ //Create status screen let notice = document.createElement('div'); notice.id = 'notice'; notice.innerHTML = '<h1>Error Message</h1><br/>'; document.getElementsByTagName('main')[0].appendChild(notice); }); }
预期结果:出现 Promise 错误时,屏幕会填充附加的 DOM 对象,并一直保持到用户采取行动。让用户有机会阅读消息。
实际结果:DOM 对象附加到<main>,填满屏幕并呈现消息,但在 2 秒内消失。
问题:如何使 .catch() 中执行的操作持续存在?
【问题讨论】:
-
我忘记在样式表中添加关键帧:
@keyframes fade-in{0%{opacity:0;}100%{opacity: 1;}}
标签: javascript css dom dynamic promise