javascript - 如何检查获取响应以调用另一个获取响应?

标签 javascript node.js promise

我尝试从 API 下载 json 文件。 为此,我需要调用 3 个端点。

http://url.com/export

它返回一个json:{"exportLoading":true,"file":"export-20190618-183316.json"}

之后,我应该调用第二个端点并检查此导出的状态:

http://url.com/export/status

它返回truefalse(当服务器正在处理时,此端点返回true。当它返回false时> 文件已完成下载。)

因此,如果status === false,我可以调用最后一个端点 http://url.com/download/file_name(我发出此请求,传递文件名(从第一个请求返回)来下载文件。

我的问题是,如何检查第二个端点是否返回 false 来发出最后一个请求并下载文件?

我刚刚做到了第二个端点。

app.get('/export', function (req, res, next) {

    global.fetch = fetch
    global.Headers = fetch.Headers;

    const headers = new Headers();
    const username = 'user';
    const password = 'pass';
    const URL = 'http://url.com/export'
    headers.set('Authorization', 'Basic ' + base64.encode(username + ":" + password));

    fetch(URL, {
        method: 'GET',
        headers: headers,
    })
    .then(res => res.json())     
    .then(json => {            
            fetch("http://url.com/exportl/status", { 
            method: 'GET',
            headers: headers,
        }).then(result => ...) 
    })
    .catch(function (error) {
        console.log(error)
      }) 
});

最佳答案

您可以使用 while 循环来调用端点,直到满足条件:

app.get('/export', async function(req, res, next) {

  global.fetch = fetch
  global.Headers = fetch.Headers;

  const headers = new Headers();
  const username = 'user';
  const password = 'pass';
  const URL = 'http://url.com/export'
  headers.set('Authorization', 'Basic ' + base64.encode(username + ":" + password));

  fetch(URL, {
    method: 'GET',
    headers: headers,
  }).then(r => r.json)
  .then(data => {
    // use data here
    var status = false
    while (!status) {
      status = await checkStatus()
    }
    // third call
  })
});


function checkStatus() {
  return fetch("http://url.com/exportl/status", {
    method: 'GET',
    headers: headers,
  }).then(r => r.json)
}

Note, I do not know the response from the status, you will have to change the code to accommodate the response.

关于javascript - 如何检查获取响应以调用另一个获取响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56665383/

相关文章:

javascript - 如何使用 queryselectorAll 方法获取多个 div id

javascript - 在没有 Webpack/Bundlers 的情况下在 PHP 中镜像 Vue 组件

node.js - 如何在调用socket.emit之前从socket.on获取响应

javascript - 有没有简单的方法来安装 TypeScript 定义?

javascript - 如何停止 Node.js/Javascript 中的无限循环

javascript - 同步独立回调结果

javascript - 带有评论框的粘性页脚,如 WhatsApp

javascript - JSPDF Autotable 断行

javascript - Angular - 从 Promise 同步获取

node.js - 无法处理 hystrix 模块中的 request-promise-json 错误