我想将数据从 Promise 推送到数组 (coursesArray),然后在其他地方使用数组值。我正在使用node-fetch库来查询API。目前,当我在 promise 内记录数组时,它具有值(coursesOne),但是当我在 promise 外记录数组时,它是空的(coursesTwo)。我该如何实现理想的解决方案,以便在 getCoursesForSitemap()
时,coursesArray 充满数据?执行
这是我到目前为止所实现的
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);
最佳答案
重构您的代码以使用async
/await
,并且不使其改变闭包外/全局变量,这应该适合您。
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);
如果您的环境不支持顶级异步/等待,您将需要执行异步代码,例如: IIFE:
(async function() {
const coursesArray = await getCoursesForSitemap();
console.log('coursesTwo', coursesArray);
}());
(该函数还将返回一个 promise ,您可以 .then()
或 await
on...)
关于javascript - 如何将数据从 Promise 推送到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58697346/