Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

javascript - 如果没有解决承诺,那么在300ms后如何模拟承诺的结果?(How mock promise's result after 300ms if promise was not resolved?)

Let's say we have a request returning not important data.(假设我们有一个返回不重要数据的请求。)

And we want get mock response if our promise not resolved since 300ms.(如果我们的承诺自300毫秒以来仍未解决,我们希望获得模拟响应。) We also have request code (for example)(我们也有请求代码(例如)) function getNotImportantData() { return fetch("url").then((response) => response.json()); } What can we do?(我们能做什么?) PS: It's ok to use es6+(PS:可以使用es6 +)   ask by Saveli Tomac translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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文档)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...