如何在里面添加延迟到承诺

如何在里面添加延迟到承诺

问题描述:

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(...)