【问题标题】:How to resolve a Promise within a loop function如何在循环函数中解决 Promise
【发布时间】:2019-09-27 17:40:12
【问题描述】:

我正在尝试发出几个异步请求,然后使用 for 循环将获得的数据推送到数组中。但是,我遇到了一个问题,即 forloop 本身不返回解析 promise 所需的值。另外,我想使用数组来渲染 GET 方法。 那么如何在 for 循环中完成 promise 并确保在为 GET 方法渲染它之前填充数组。对不起,我的英语不好。我对异步概念还很陌生,如果可能的话,请用简单的语言教我。另外,如果有更好的方法来解决我想知道的问题。

const currencyName = ["btc", "eth", "xrp"];
let dataCollections = [];
for (i = 0; i < currencyName.length; i ++) {
  dataCollections.push(new Promise(function(resolve, reject) {
    request.get(`https://apiv2.bitcoinaverage.com/indices/global/ticker/${currencyName[i]}jpy`, function(error, response, body) {
      if (error) {
        reject(error);
      } if (dataCollections.length === 3) {
        dataColletions = [];
      }  else {
        resolve(JSON.parse(body));
      }
    });
  }));
}

//Promise.all(??).then(??)

//For rendering dataCollections
  app.get("/", function(req, res) {
    res.render("home", {dataCollections: dataCollections});
}

【问题讨论】:

  • mapcurrencyName 数组上,并产生一组promise。然后使用Promise.all 管理响应。这样你就不需要循环了。
  • 删除那个奇怪的if (dataCollections.length === 3) { dataColletions = []; } 部分,然后只做Promise.all(dataCollections).then(jsonBodies =&gt; { … })
  • 您想在应用程序启动时仅获取一次数据,还是在每次请求时获取数据?
  • 听起来像XY problem。与其解释你想要做什么,不如试着专注于解释你想要实现的目标。
  • 感谢您的建议。每次重新加载页面时,我都会尝试获取数据。但我通过将所有代码放入 GET 方法来解决它。是的,我认为我遇到了 XY 问题。

标签: javascript node.js express asynchronous


【解决方案1】:

1) 考虑将您的数组命名为 currencyNames 复数,以便您可以将迭代器命名为 currencyName

2) 您的 for 循环正在重新发明 array.map 函数。考虑改用array.map

3) 你的 for 循环有一个不可能的 if 子句 (if (dataCollections.length === 3)),这也意味着 else 子句在错误的 if 语句上。我认为这是一个错字。

现在回到您问题的核心,是的,Proimse.all(Array&lt;Promise&gt;) 就是您想要的;它在其参数中的所有元素都解析时解析。

const currencyNames = ["btc", "eth", "xrp"];

let dataCollections = currencyNames.map(currencyName => new Promise((resolve, reject) =>
    request.get(`https://apiv2.bitcoinaverage.com/indices/global/ticker/${currencyName}jpy`, (error, response, body) => {
      if (error)
        reject(error);
      else
        resolve(JSON.parse(body));
    })));

//For rendering dataCollections
app.get("/", async (req, res) =>
    res.render("home", {dataCollections: await Promise.all(dataCollections)}));

【讨论】:

  • 它就像一个魅力!感谢您的帮助。我很感激。上帝保佑你
【解决方案2】:

使端点异步:

 app.get("/", async function(req, res) {
   res.render("home", {dataCollections: await Promise.all(dataCollections) });
 });

【讨论】:

    猜你喜欢
    • 2014-10-15
    • 2019-08-10
    • 1970-01-01
    • 2018-04-28
    • 2020-05-10
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多