[英]Learning Promises, Async/Await to control execution order
我一直在研究 promise、await 和 async 函数。 当我刚刚在学习 Promise 的阶段时,我意识到以下几点:当我发送两个请求时,并不能保证它们会按照它们在代码中编写的顺序来。 当然,一个网络的路由和数据包。 当我运行下面的代码时,请求将不按特定顺序解决。
const getCountry = async country => {
await fetch(`https://restcountries.com/v2/name/${country}`)
.then(res => res.json())
.then(data => {
console.log(data[0]);
})
.catch(err => err.message);
};
getCountry('portugal');
getCountry('ecuador');
在这一点上,我还没有了解异步和等待。 所以,下面的代码完全按照我想要的方式工作。 每个请求都等到另一个请求完成。
这是最简单的方法吗? 有没有我可以删除的冗余? 我不需要大量替代示例。 除非我做错了什么。
await fetch(`https://restcountries.com/v2/name/${country}`)
.then(res => res.json())
.then(data => {
console.log(data[0]);
})
.catch(err => err.message);
};
const getCountryData = async function () {
await getCountry('portugal');
await getCountry('ecuador');
};
getCountryData();
提前致谢,
我按照@deceze 推荐的方式进行了尝试,效果很好:我删除了所有.then
并用await
替换了它们。 这样干净多了。 现在我可以使用普通的 try 和 catch 块了。
// GET COUNTRIES IN ORDER
const getCountry = async country => {
try {
const status = await fetch(`https://restcountries.com/v2/name/${country}`);
const data = await status.json();
renderCountry(data[0]); // Data is here. Now Render HTML
} catch (err) {
console.log(err.name, err.message);
}
};
const getCountryData = async function () {
await getCountry('portugal');
await getCountry('Ecuador');
};
btn.addEventListener('click', function () {
getCountryData();
});
谢谢你们。
是的,这是正确的做法。 请务必意识到,您正在阻止每个请求,因此它们一次运行一个请求,从而导致效率低下。 正如我所提到的,JavaScript 的美妙之处在于它的异步性,所以要好好利用它。 您可以几乎同时运行所有请求,从而使您的请求大大加快。 举个例子:
// get results... const getCountry = async country => { const res = await fetch(`https://restcountries.com/v2/name/${country}`); const json = res.json(); return json; }; const getCountryData = async countries => { const proms = countries.map(getCountry); // create an array of promises const res = await Promise.all(proms); // wait for all promises to complete // get the first value from the returned array and sort based on input return res.map(r => r[0]).sort((a, b) => { if (countries.indexOf(a.name.toLowerCase()) > countries.indexOf(b.name.toLowerCase())) return 1; if(countries.indexOf(a.name.toLowerCase()) < countries.indexOf(b.name.toLowerCase())) return -1; return 0; }); }; // demo: getCountryData(['portugal', 'ecuador']).then(console.log); // it orders by the countries you ordered getCountryData(['ecuador', 'portugal']).then(console.log);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.