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

时间:2019-04-28 01:51:29

标签: javascript node.js express promise

我想在我的应用中创建一个“取消”按钮。该按钮旨在取消的请求包含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请求的过程中取消它并完全中止它?

2 个答案:

答案 0 :(得分:1)

您将使用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);
    });
});

答案 1 :(得分:0)

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