繁体   English   中英

项目未被推送到 Javascript promise 内的数组

[英]Items not getting pushed to an array inside the Javascript promise

在以下从 Nextjs 应用导出的 function 作为 API 页面中, domainnames数组在 200 响应中不返回任何内容。

但是,如果我不使用GetDomainStatus() function 并且只是将项目从response.data.results推送到domainnames ,那么 JSON 响应将被填充。

export default function GetSuggestions(req, res){
const keyword = req.query.q;
const tlds = '.com,.net,.io,.org,.co,.xyz,.app,.us,.blog,.shop,.land,.video,.review,.host,.dev';
let queryPath = `${suggestionsURL}?include-registered=false&tlds=${tlds}&include-suggestion-type=true&sensitive-content-filter=true&use-numbers=true&max-length=20&lang=eng&max-results=100&name=${keyword}&use-idns=false`
let domainnames = [];

axios.get(queryPath).then(response => {

  response.data.results.forEach(item => {

      GetDomainStatus(item.name).then(a => {
        domainnames.push({
          name: item.name,
          avail: a
        })
      })
  })
  res.status(200).json(domainnames);
});

}

这是一个 scope 问题,我实际上无法从 promise 中访问domainnames数组吗?

该解决方案有效。 不确定它是否最好,但使用 promise.all 解决方案。

const domainnames = [];
const promises = [];

axios.get(queryPath).then(response => {

  response.data.results.forEach(item => {

    let newPromise = GetDomainStatus(item.name).then(a => {
        domainnames.push({
          name: item.name,
          avail: a
        })
    });
    promises.push(newPromise);
  })
  Promise.all(promises).then(r => res.status(200).json(domainnames));

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM