# 模拟实现async

async是基于generator的

真实使用

```javascript
async function fn(args) { ... }

// 可以以下来模拟
const asyncFn = wrap(fn)
asyncFn(args) 
```

简版实现

```javascript
const wrap = (genFn) =>{
	return (...args) => new Promise((resolve, reject) => {
  	const g = genFn(...args)
    function step(data){
    	const res = g.next(data)
      if(!res.done){
      	Promise.resolve(res.value).then(step)
      }else{
      	resolve(res.value)
      }
    }
    step()
  })
}
```

完整实现

```javascript
const wrap = (genFn) =>{
	return (...args) => new Promise((resolve, reject) => {
  	const g = genFn(...args)
    function stepF(nextFn){
    	try{
      	const res = nextFn()
      } catch (e){
      	return reject(e)
      }
      if(res.done){
      	return resolve(res.value)
      }
      
      Promise.resolve(res.value).then( v => {
      	stepF( () => g.next(v))
      }, e => {
      	stepF( () => g.throw(e))
      })
    }
    stepF( () => g.next())
  })
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://mm.ricky.moe/javascript/chang-jian-han-shu/mo-ni-shi-xian-async.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
