【问题标题】:Pass value of response from an async request to the next request将异步请求的响应值传递给下一个请求
【发布时间】:2018-06-22 17:50:21
【问题描述】:

我需要从端点获取一些结果及其结构方式,响应告诉我下一组结果使用哪个端点(当前限制每个请求 1k 行),直到获得所有结果.然后我需要将数据重新拼接在一起。

我可以使用以下代码相对轻松地获取一组结果,但很难理解如何等待结果才能获取下一组结果,除非我嵌套它,而且我不想这样做因为我不知道我需要预先获取多少组结果。

var headers = {
  'Content-type': 'application/json',
  'X-DBX-AUTH-TOKEN': 'yyy@zzz.com/6573846tf9334e'
};

var options_results = {
  method: 'GET',
  headers: headers,
};

var url = 'https://endpoint/execute/{uuid}/0';
options_results.url = url;

function fetchResults(error, response, body) {
  console.log(body);
  var next_uid = JSON.parse(body.uuid);
}

request(options_results, fetchResults);

我已经阅读了 Promise 等内容,但仍在努力如何在这里应用它。任何帮助将不胜感激!

【问题讨论】:

标签: javascript node.js callback promise request


【解决方案1】:

您可以将您的请求回调函数转换为promise。代码如下所示:

var requestPromise = options =>
  new Promise(
    (resolve,reject)=>
      request(
        options,
        (error,response,body)=>
          (error)
            ? reject(error)
            : resolve([body,response])
      )
  );

requestPromise(
  {
    url:'https://endpoint/execute/{uuid}/0',
    method: 'GET',
    headers: {
      'Content-type': 'application/json',
      'X-DBX-AUTH-TOKEN': 'yyy@zzz.com/6573846tf9334e'
    }
  }  
)
.then(
  ([body])=>{
    var next_uid  = JSON.parse(body.uuid);
    //make next request
    return requestPromise(
      {
        url:'https://endpoint/execute/{uuid}/0',
        method: 'GET',
        headers: {
          'Content-type': 'application/json',
          'X-DBX-AUTH-TOKEN': 'yyy@zzz.com/6573846tf9334e'
        }
      }          
    )
  }
)
.then(
  ([body,response])=>{
    console.log("made other request:",body,response);
  }
)
.catch(
  err=>console.error("something went wrong:",err)
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2020-07-31
    • 2022-11-18
    • 2020-11-08
    • 1970-01-01
    • 2010-12-30
    相关资源
    最近更新 更多