簡體   English   中英

如何等待多個 API 調用 reutrn?

[英]How to wait for multiple API calls to reutrn?

我有一組要查詢的 API。 例如var urls = ['example.org?x=1', 'example.org?x=2,3']如何讓 ReactJS 在響應客戶?

我已經嘗試修改@Shanoor's answer from Promises with http.get node.js但客戶端的結果是空的( "" )。

var http = require('http');
var urls = ['example.org', 'example2.org', '...'];

var done = 0;
var result = [];

function callback(index, data) {
  result[index] = data;
  done++;
  if (done == urls.length) {
    result.forEach(console.log);
    //I tried using the resp object here to return result[] but the data seemed corrupt 
  }
}

function processUrl(url, index) {
  var finalData = '';
  http.get(url, function(response) {
    response.setEncoding('utf8');
    response.on('data', function(data) {
      finalData += data;
    });
    response.on('error', console.error);
    response.on('end', function() {
      callback(index, finalData);
    })
  });
}

app.get("/api/blah", (resp) => {
  urls.forEach(processUrl);
  //resp(result); this would result in an empty response
}

您可以使用 Promise 來做到這一點,應該是這樣的

function processUrl(url, index) {
  var finalData = '';

  return new Promise((resolve, reject) => {
    http.get(url, function(response) {
      response.setEncoding('utf8');
      response.on('data', function(data) {
        finalData += data;
      });
      response.on('error', reject);
      response.on('end', function() {
        resolve(finalData);
      })
    });
  })
}

app.get("/api/blah", (resp) => {
  Promise.all(urls.map(processUrl)).then(function(results) {
    console.log(results);
  });
}

請注意,我沒有檢查代碼是否正常工作,因此請閱讀有關PromisesPromise.all()方法的更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM