我正在使用 Promises,同时我有一个加载动画。
问题是我的 promise 很快就得到了解决,而加载程序很快就消失了。
所以我想启动一个 Promise,如果 Promise 在 3 秒之前得到解决,则等待剩余时间。
示例
export const operation = () => {
const a = new Date();
const myPromise = doAction().then(() => {
const b = new Date();
if((b - a) < 3000)
operationIsDone();
else
setTimeout(() => {operationIsDone();}, b - a)
});
}
有npm或者更好的方法吗? 提前致谢。
最佳答案
使用仅运行最短等待时间的第二个 promise 要容易得多。然后使用 Promise.all 等待两者完成。
这样,您的脚本将始终至少等待默认延迟,但如果 yourOwnPromise
花费的时间比该延迟更长,则等待时间也会更长。
const wait = delay => new Promise(resolve => setTimeout(resolve, delay));
const doAction = () => wait(500); // TODO replace this with your own function
const yourOwnPromise = doAction();
yourOwnPromise.then(() => {
console.log('yourOwnPromise resolved now');
});
Promise.all([yourOwnPromise, wait(3000)]).then(() => {
console.log('both resolved now');
});
参见Promise.all
了解详情。
关于javascript - promise 解决得太快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50001394/