我知道下面的代码,将输出resolved
.我的问题是这有什么用,在 react、node 等构建现实世界的应用程序时,异步/等待什么时候有用?
function foo() {
const resolveAfter2Seconds = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall(){
console.log('calling');
var result = await resolveAfter2Seconds();
console.log(result);
}
return asyncCall;
}
const myFoo = foo()
myFoo();
网络、文件和频繁的承诺
我相信您会遇到的最常见的问题会让您想要将当前功能切换到async
模式通常与以下方面有关:网络请求、文件操作以及承诺的频繁使用和/或嵌套。
网络请求
当我编写网络请求时,我总是使用 async/await
await 组合。对我来说,它使我的代码更加线性和可读性。我也不必担心完成后fetch
(或axios
)的回报
async function getPins(user, filterValue) {
const pins = await axios.get(...);
if (filterValue) {
return pins.filter(pin => pin.title.includes(filterValue));
}
return pins;
}
文件
async function handleFile(data, isEncrypted, isGzipped) {
if (isEncrypted) {
data = await decrypt(data, secret);
}
if (isGzipped) {
data = await ungzip(data);
}
return data;
}
频繁的承诺
async function init() {
const activeBoard = await getActiveBoard();
const boardMembers = await getBoardMembersFrom(activeBoard);
const allTasks = [];
for await (const tasks of boardMembers.map(getTasks)) {
allTasks.push(task);
this.setState({ tasks: [...allTasks] });
}
}
注意:您可以将async/await
与承诺一起使用。没有必要将自己限制在一个或另一个。
const test = async props => {
const data = await fetch('...').then(res => res.json());
console.log(data) /* do what you want with the data now */
}