Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【面经】美团 二面5:用 promise 实现一个请求超时功能 #7

Open
liam61 opened this issue Mar 21, 2019 · 2 comments
Open
Labels
面经 面经

Comments

@liam61
Copy link
Owner

liam61 commented Mar 21, 2019

用 promise 实现一个请求超时功能

关键词:promise.then 与 setTimeout 并行

抓住 promise 的状态只能由 pending -> fulfilled,或者 pending -> rejected,并且只能进行一次改变

function promiseWithTimeout(url, timeout = 3000) {
  return new Promise((resolve, reject) => {
    fetch(url).then(data => data.json()).then(data => resolve(data)); // fetch 先得到结果就 resolve
    setTimeout(() => reject(Error('time is out!')), timeout); // 时间到了还没 fetch 到就 reject
  });
}

promiseWithTimeout('http://localhost:8080/data.json')
  .then(data => console.log(data))
  .catch(err => console.error(err));

// server.js 测试
const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors({ origin: '*' }));

app.use('/data.json', (req, res) => {
  setTimeout(() => res.end(JSON.stringify({ a: 1 })), Math.floor(Math.random() * 6 * 1000));
});

app.listen(8080, () => console.log('the app is running at http://localhost:8080'));
@liam61 liam61 added the 面经 面经 label Mar 21, 2019
@liam61 liam61 changed the title 【面经】美团 二面:用 promise 实现一个请求超时功能 【面经】美团 二面5:用 promise 实现一个请求超时功能 Mar 27, 2019
@DualWield
Copy link

DualWield commented Sep 15, 2021

也可以使用Promise.race

@liam61
Copy link
Owner Author

liam61 commented Sep 15, 2021

也可以使用Promise.race

@DualWield 是呀,本质就是在问 race 实现

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
面经 面经
Projects
None yet
Development

No branches or pull requests

2 participants