两个例子:
- 利用 async/await 将 异步请求转换成 同步请求;
- generator 自动执行 next();
async / await
将异步方法转换成异步方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| function sleep(time) { return new Promise((resolve, reject)=> { setTimeout(()=>{ resolve(100); }, time); }) } async function testSleep() { console.time('sleep1000'); let obj = await sleep(1000); console.timeEnd('sleep1000'); console.log(obj); } testSleep();
|
将一个异步方法转换成同步方法,其实就是将一个带有 callback 回调方法的函数,包装成一个 Promise 对象返回;
将 fetch 转换成 同步方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| function asyncPromise(promise) { function then(p) { if (p.then) { return p.then(data=> { return then(data) }); } else { return p; } } return then(promise); } async function test() { let fetch_test = await fetch('http://127.0.0.1:8000'); let promise = await fetch_test.json(); let result = await asyncPromise(promise); console.log('----------result----------'); console.log(result); } test();
|
1 2 3 4 5 6 7 8 9 10 11 12
| import fetch from 'isomorphic-fetch'; async function asyncFetch() { try { let response = await fetch('http://127.0.0.1:8000'); let data = await response.json(); console.log(data); } catch (e) { console.log("Oops, error", e); } } asyncFetch();
|
generator / yield
自动执行 generator,将 fetch 转换成同步 fetch;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import fetch from 'isomorphic-fetch'; function co(generator, ...params) { var gen = generator(...params); function next(generation) { if (generation.done) return generation.value; return generation.value.then(data => next(gen.next(data))); } return next(gen.next()); } function *generateFetch(url) { let response = yield fetch(url); let json = yield response.json(); return json; } async function req2() { console.time('fetch'); let wtf = await co(generateFetch, 'http://127.0.0.1:8000'); console.timeEnd('fetch'); console.log(wtf); return wtf; } req2();
|