- Objective:
- Breadcrumb:
# 概念阐释
# 实例
# 相关内容
# 问题
写一个async...await异步编程函数,结果为
```bash
1. Heading to the store to buy beans...
2. I bought ${garbanzo} beans because they were on sale.
3. Great! I'm making ${garbanzo} beans for dinner tonight!
```
```js
//library.js
const shopForBeans = () => {
return new Promise((resolve, reject) => {
const beanTypes = ['kidney', 'fava', 'pinto', 'black', 'garbanzo'];
setTimeout(()=>{
let randomIndex = Math.floor(Math.random() * beanTypes.length);
let beanType = beanTypes[randomIndex];
console.log(`2. I bought ${beanType} beans because they were on sale.`);
resolve(beanType);
}, 1000);
});
}
module.exports = shopForBeans;
```
# 问题答案
```js
const shopForBeans = require('./library.js');
async function getBeans() {
console.log(`1. Heading to the store to buy beans...`);
let value = await shopForBeans();//resolve(beanType);的结果
console.log(`3. Great! I'm making ${value} beans for dinner tonight!`);
}
getBeans();
```
当调用`getBeans`时发生的顺序
1. 打印 1. Heading to the store to buy beans...
2. 由于 `await` 的存在,JS会“暂停”在这里,等待 `shopForBeans` 的Promise解决。等待`setTimeout`1秒的延迟
3. 1秒后打印 2. I bought ${beanType} beans because they were on sale.
4. await已经有了解决值 resolve bean的类型,这个值被赋给value变量(如果console.log(value))就会看到
5. value值传入3. Great! I'm making ${value} beans for dinner tonight!
# 参考资料
- [课后练习](https://www.codecademy.com/journeys/full-stack-engineer/paths/fscj-22-front-end-development/tracks/fscj-22-async-javascript-and-http-requests/modules/wdcp-22-learn-javascript-syntax-async-await-40c16baa-3867-4d62-917d-5b66da1a85f5/lessons/async-await/exercises/writing-async-functions)