【问题标题】:Creating a cancel button... how to completely abort a request in Node/Express.js创建取消按钮...如何在 Node/Express.js 中完全中止请求
【发布时间】:2019-09-17 01:48:25
【问题描述】:

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

如果我有这样的路线:

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 请求的过程中取消它并完全中止它?

【问题讨论】:

  • 您可以在对router.get 的回调中设置两个承诺:一个执行现有的fetch().then...,另一个等待(或反复检查)cancel 事件(例如按钮点击)来触发。您可以使用Promise.race 响应先发生的任何一个而忽略另一个。如果cancel 事件从未发生,则fetch... 序列获胜。 (一旦调用了 Promise,就不能真正“取消”它,但您可以选择忽略结果。)
  • 比如原生nodejs请求有一个abort方法
  • @JaromandaX 当然可以 - npmjs.com/package/…
  • @BenjaminGruenbaum - 好的,所以,这不像在浏览器中获取:p
  • @JaromandaX 你也可以在浏览器中取消获取:]

标签: javascript node.js express promise


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    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);
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2016-02-02
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 2023-04-04
      • 2016-11-14
      • 2011-05-31
      相关资源
      最近更新 更多