Javascript 如何在里面添加延迟到承诺
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38956121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add delay to promise inside then
提问by Tuomas Toivonen
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?
我如何在后者中添加延迟然后阻止,以便在将控制权传递给 fetch 调用者然后阻止之前等待指定的时间?
回答by
Return a promise from the then
handler that waits:
从then
等待的处理程序返回一个承诺:
.then(() => new Promise(resolve => setTimeout(resolve, 1000)))
If you want to "pass through" the value of the promise, then
如果你想“传递”promise 的值,那么
.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 use it as in
然后像这样使用它
.then(sleeper(1000)).then(...)
回答by T.J. Crowder
This is one of the rare situations you create a new promise:
这是您创建新承诺的罕见情况之一:
fetch() {
return axios.get('/rest/foo')
.then(value => new Promise(resolve => {
setTimeout(() => {
resolve(value);
}, delayInMilliseconds);
})
);
}
But rather than a one-off, I'd have (in fact, do have) a utility function:
但不是一次性的,我会有(事实上,确实有)一个效用函数:
function wait(ms, value) {
return new Promise(resolve => setTimeout(resolve, ms, value));
}
Then:
然后:
fetch() {
return axios.get('/rest/foo')
.then(value => wait(delayInMilliseconds, value));
}