Tuo*_*nen 43 javascript asynchronous callback promise
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
}
Run Code Online (Sandbox Code Playgroud)
如何在后者中添加延迟然后阻塞,因此它会在将控制传递给提取调用者然后阻塞之前等待指定的时间量?
小智 101
从then等待的处理程序返回一个promise :
.then(() => new Promise(resolve => setTimeout(resolve, 1000)))
Run Code Online (Sandbox Code Playgroud)
如果你想"通过"承诺的价值,那么
.then(x => new Promise(resolve => setTimeout(() => resolve(x), 1000)))
Run Code Online (Sandbox Code Playgroud)
要在任何地方避免使用此样板,请编写实用程序函数:
function sleeper(ms) {
return function(x) {
return new Promise(resolve => setTimeout(() => resolve(x), ms));
};
}
Run Code Online (Sandbox Code Playgroud)
然后用它作为
.then(sleeper(1000)).then(...)
Run Code Online (Sandbox Code Playgroud)
T.J*_*der 11
这是您创建新承诺的罕见情况之一:
fetch() {
return axios.get('/rest/foo')
.then(value => new Promise(resolve => {
setTimeout(() => {
resolve(value);
}, delayInMilliseconds);
})
);
}
Run Code Online (Sandbox Code Playgroud)
但不是一次性的,我会有(事实上,确实有)一个效用函数:
function wait(ms, value) {
return new Promise(resolve => setTimeout(resolve, ms, value));
}
Run Code Online (Sandbox Code Playgroud)
然后:
fetch() {
return axios.get('/rest/foo')
.then(value => wait(delayInMilliseconds, value));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38283 次 |
| 最近记录: |