目前正在尝试自学Promises如何在JavaScript中工作。
所以我想创建一个承诺,在其中我进行复杂的计算。如果该计算按时成功完成,我希望 Promise 解析,但如果计算时间过长,Promise 应拒绝并出现超时错误。可用时间是预定义的,例如1000ms。
我的示例代码如下所示:
new Promise((resolve, reject) => {
const result = complexCalculation();
return resolve(result); //this should be called when complexCalculation completed in under 1000ms
return reject('timeout error'); //and this if 1000ms have passed without getting a result
})
.then(result => {
console.log(result);
})
.catch(err => {
console.log(err);
});
我已经尝试了不同的东西,比如异步函数和 setTimeout,但没有一个像我试图实现它的方式那样工作。总的来说,我对JS仍然很陌生,所以请耐心等待。
下面是一个如何设置带有超时拒绝的承诺的示例:
function calcWithTimeout(timeout) {
return new Promise((resolve, reject) => {
// start timeout
const timeoutID = setTimeout(
() => reject('longCalculation took too long'),
timeout
);
// start calculation
longCalculation().then(result => {
clearTimeout(timeoutID);
resolve(result);
});
});
}
// a fake calculation that takes 1 second
function longCalculation() {
return new Promise(resolve => {
setTimeout(() => {
resolve('your calculation completed');
}, 1000);
});
}
const pre = document.getElementById('result');
const myFn = (timeout) => {
pre.innerHTML = 'calling calcWithTimeout with timeout = ' +
timeout + 'n';
calcWithTimeout(timeout)
.then(result => {
pre.innerHTML += 'result: ' + result;
})
.catch(err => {
pre.innerHTML += 'error: ' + err;
});
}
#result {
background-color: #eee;
padding: 0.5rem;
}
<button onclick="myFn(2000)">Long Timeout</button>
<button onclick="myFn(500)">Short Timeout</button>
<pre id="result"></pre>