如何将数据从Promise推送到数组

我想将数据从promise推送到数组(coursesArray),然后在其他地方使用数组值。我正在使用node-fetch库来查询API。当前,当我在promise中记录数组时,它具有values(coursesOne),但是当我在promise中记录数组时,它是空的(coursesTwo)。我该如何实施理想的解决方案,以便在执行getcoursesForSitemap()时将课程数组充满数据

这是我到目前为止已经实现的

const coursesArray = [];

const getcoursesForSitemap = () => {
  fetch(coursesUrl)
    .then(res => res.json())
    .then(json => {
      json.courses.results.map(course => {
        return coursesArray.push(course.slug);
      });
      console.log('coursesOne',coursesArray);
    })

    .catch(error => {
      console.log(error);
    });
};
getcoursesForSitemap();
console.log('coursesTwo',coursesArray);
fuchen333 回答:如何将数据从Promise推送到数组

将您的代码重构为使用DATEDIFF() / async,并且不使其变为闭包/全局变量,这应该对您有用。

await

如果您的环境不支持顶级异步/等待,则您需要执行异步代码,例如IIFE:

const getCoursesForSitemap = async () => {
  const result = await fetch(coursesUrl);
  const json = await result.json();
  return json.courses.results.map(course => course.slug);
};
const coursesArray = await getCoursesForSitemap();
console.log('coursesTwo',coursesArray);

(该函数还会返回一个承诺,您可以在(async function() { const coursesArray = await getCoursesForSitemap(); console.log('coursesTwo',coursesArray); }()); .then()上使用...)

,

您正在尝试记录这些值,然后将其从您的诺言中解决。这就是为什么它不起作用。您需要等待Promise解决之后才能尝试向他们展示。

您还需要兑现承诺。

const coursesArray = [];

const getCoursesForSitemap = () => {
  return fetch(coursesUrl)
    .then(res => res.json())
    .then(json => {
      json.courses.results.forEach(course => {
        return coursesArray.push(course.slug);
      });
      console.log('coursesOne',coursesArray);
    })

    .catch(error => {
      console.log(error);
    });
};
getCoursesForSitemap().then(() => {
    console.log('coursesTwo',coursesArray);
});

我还更改了用于map的{​​{1}}函数,因为您不需要更改forEach数组的值。

本文链接:https://www.f2er.com/3165275.html

大家都在问