首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >正在创建取消按钮...如何在Node/Express.js中完全中止请求

正在创建取消按钮...如何在Node/Express.js中完全中止请求
EN

Stack Overflow用户
提问于 2019-04-28 09:51:29
回答 2查看 736关注 0票数 1

我想在我的应用程序中创建一个“取消”按钮。按钮要取消的请求包含一个Promise.all,由于另一端的API速率限制,该请求通常需要几分钟才能完成。

如果我有一个这样的路由:

代码语言:javascript
运行
复制
router.get('/api/my_route', (req, res, next) => {

//imagine this takes about 2 minutes to complete and send back the 200.
//The user changes their mind and wants to cancel it at the 1 minute mark.

  fetch("https://jsonplaceholder.typicode.com/albums")
    .then(first_response => first_response.json())
    .then(arr => Promise.all(arr.map(item => 
       fetch("https://jsonplaceholder.typicode.com/users")
       .then(second_response => second_response.json())
       .then(value => console.log(value))
      )))
    .then(() => {
        res.status(200);   
    });
});

如何在发出Promise请求的过程中取消它并完全中止它?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-04-28 17:42:10

您可以使用AbortController来中止获取请求,并监听请求上的close事件,以了解客户端关闭了连接:

代码语言:javascript
运行
复制
router.get('/api/my_route', (req, res, next) => {
  // we create a new AbortController to abort the fetch request
  const controller = new AbortController();
  const signal = controller.signal;

  req.on('close', err => { // if the request is closed from the other side
    controller.abort(); // abort our own requests
  })


  fetch("https://jsonplaceholder.typicode.com/albums", {signal})
    .then(first_response => first_response.json())
    .then(arr => Promise.all(arr.map(item => 
       fetch("https://jsonplaceholder.typicode.com/users", {signal})
       .then(second_response => second_response.json())
       .then(value => console.log(value))
      )))
    .then(() => {
        res.status(200);
    });
});
票数 1
EN

Stack Overflow用户

发布于 2019-04-28 11:22:39

承诺本身没有取消的机制。您可能会向远程服务器发送另一个api请求,以取消原始请求,但如果该请求受到速率限制,则表明它是一个较旧的服务器,可能不容易更改。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55886372

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档