如何在里面添加延迟到承诺 [英] 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
}
如何在后者中添加延迟然后阻塞,以便在将控制权传递给 fetch 调用者然后阻塞之前等待指定的时间?
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?
推荐答案
从等待的 then
处理程序返回一个承诺:
Return a promise from the then
handler that waits:
.then(() => new Promise(resolve => setTimeout(resolve, 1000)))
如果你想传递"promise的值,那么
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屋!
查看全文