3 回答

TA貢獻(xiàn)1795條經(jīng)驗(yàn) 獲得超7個(gè)贊
這里有幾件事。您不需要將 .then() 鏈接到 fetch() 上。fetch() 返回一個(gè)承諾。Array.prototype.map() 返回一個(gè)數(shù)組??偠灾阕罱K會(huì)得到一系列的承諾。您可以使用 Promise.all(arrayOfPs) 解析 Promise 數(shù)組
編輯:在您發(fā)表評(píng)論并審查您的問題后,我重寫了此內(nèi)容,以便它從過濾后的存儲(chǔ)庫列表中檢索技能。
const url = `https://api.github.com/users/RodrigoWebDev/repos?per_page=100&sort=created`;
(async() => {
// Final results
let results;
try {
// Get all repositories
const repos = await fetch(url).then((res) => res.json());
const responses = await Promise.all(
// Request file named 'build-with.json' from each repository
repos.map((item) => {
return fetch(
`https://raw.githubusercontent.com/${item.full_name}/master/built-with.json`
);
})
);
// Filter out all non-200 http response codes (essentially 404 errors)
const filteredResponses = responses.filter((res) => res.status === 200);
results = Promise.all(
// Get the project name from the URL and skills from the file
filteredResponses.map(async(fr) => {
const project = fr.url.match(/(RodrigoWebDev)\/(\S+)(?=\/master)/)[2];
const skills = await fr.json();
return {
project: project,
skills: skills
};
})
);
} catch (err) {
console.log("Error: ", err);
}
results.then((s) => console.log(s));
})();

TA貢獻(xiàn)2039條經(jīng)驗(yàn) 獲得超8個(gè)贊
問題是提取沒有被返回,因此 .map() 返回未定義。我可以建議使用 async-await 的解決方案嗎?
const url = "https://api.github.com/users/RodrigoWebDev/repos?per_page=100&sort=created";
getData(url).then(data => console.log(data));
async function getData(url){
const response = await fetch(url);
const data = await response.json();
const arrOfPromises = data.map(item => fetch(`https://raw.githubusercontent.com/${item.full_name}/master/built-with.json`)
);
return Promise.all(arrOfPromises);
}

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個(gè)贊
您有多個(gè)問題:
在地圖函數(shù)內(nèi)部,您不返回任何結(jié)果
地圖函數(shù)的結(jié)果實(shí)際上是另一個(gè) Promise(因?yàn)閮?nèi)部有 fetch)。
那么你需要做什么:
從地圖返回承諾 - 因此你將擁有一系列承諾
使用 Promise.all 等待第 1 點(diǎn)中的所有承諾
像這樣的東西:
var url1 = "https://api.github.com/users/RodrigoWebDev/repos?per_page=100&sort=created";
var datum = fetch(url1)
.then((response) => response.json())
.then((data) => {
return Promise.all(data.map(item => {
//item.full_name returns the repositorie name
return fetch(`https://raw.githubusercontent.com/${item.full_name}/master/built-with.json`)
.then(data => {
item["filters"] = data
return item
})
}));
}).then(data => console.log(data))
添加回答
舉報(bào)