如何在内部添加延迟承诺 [英] How to add delay to promise inside then
本文介绍了如何在内部添加延迟承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
fetch() {
return axios.get('/rest/foo')
//.then(response => {throw new Error(response)}) // Uncomment to test network error
//.then( <<add delay here>> ) // Uncomment to simulate network delay
}
如何在后者阻塞时添加延迟,因此在将控制传递给提取调用者然后阻塞之前它将等待指定的时间量?
How do I add delay in the latter then block, so it will wait specified amount of time before passing control to the fetch callers then blocks?
推荐答案
从等待的然后
处理程序返回一个承诺:
Return a promise from the then
handler that waits:
.then(() => new Promise(resolve => setTimeout(resolve, 1000)))
如果你想通过承诺的价值,那么
If you want to "pass through" the value of the promise, then
.then(x => new Promise(resolve => setTimeout(() => resolve(x), 1000)))
要避免在任何地方使用此样板,请编写一个实用程序函数:
To avoid this boilerplate everywhere, write a utility function:
function sleeper(ms) {
return function(x) {
return new Promise(resolve => setTimeout(() => resolve(x), ms));
};
}
然后将其用作
.then(sleeper(1000)).then(...)
这篇关于如何在内部添加延迟承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文