Well, in this case we can use standard Promise
API.(好吧,在这种情况下,我们可以使用标准的Promise
API。)
Let's do it step by step:(让我们逐步进行:)
We can make another promise which is guaranteed to be resolved in around 300ms with mock payload(我们可以做出另一个保证,即保证在约300毫秒内通过模拟有效载荷解决)
const mockPromise = new Promise((resolve) => {
setTimeout(() => {
resolve([]); // any payload, here is empty array for example
}, 300);
});
Also we can use Promise.race
method for detect who resolved the first(我们也可以使用Promise.race
方法检测谁解决了第一个)
function getNotImportantData() {
return fetch("url").then((response) => response.json());
}
const mockPromise = new Promise((resolve) => {
setTimeout(() => {
resolve([]); // any payload, here is empty array for example
}, 300);
});
Promise.race([
getNotImportantData(),
mockPromise,
]);
In the end we can wrap our code to useful function(最后,我们可以将代码包装为有用的功能)
function getNotImportantData() {
return fetch("url").then((response) => response.json());
}
function tryOrMock(promise, mock, timeout) {
const mockPromise = new Promise((resolve) => {
setTimeout(() => {
resolve(mock);
}, timeout);
});
return Promise.race([
promise,
mockPromise,
]);
}
tryOrMock(getNotImportantData(), [], 300)
.then((firstResult) => {
console.log(firstResult);
})
.catch((error) => {
// don't forget to handle exceptions
})
// or async/await syntax
try {
const firstResult = await tryOrMock(getNotImportantData(), [], 300);
} catch (e) {
// handle exceptions here too
}
I put here reference to Promise.race
docs(我在这里引用了Promise.race
文档) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…