## 區分同步代碼和異步代碼
在實際開發中,使用 then 方法會將任何同步代碼封裝為異步代碼,比如
```
const f = () => console.log('now');
Promise.resolve().then(f);
console.log('next');
```
執行結果為先輸出 `next` 在輸出 `now`
有沒有一種方法,讓同步函數同步執行,異步函數異步執行 ?
如果想讓 Promise 區分同步代碼和異步代碼,則可以有以下兩種解決方案 :
方法一: 使用 async 立即執行函數
```
const f = () => console.log('now');
(async () => f())();
console.log('next');
```
以上代碼,先輸出 `now`,后輸出 `next`
如果執行的是異步代碼,則可以使用 then 進行返回 :
```
const f = () => Promise.resolve('now');
(async () => f())().then(console.log);
console.log('next');
```
以上代碼,先輸出 `next`,后輸出 `now`
方法二: 使用 `new Promise()` 立即執行函數
```
const f = () => console.log('now');
( () => new Promise( resolve => resolve(f()) ) )();
console.log('next');
```
以上代碼,先輸出 `now`,后輸出 `next`
同樣的,如果是異步代碼,則可以使用 then 返回 :
```
const f = () => Promise.resolve('now');
( () => new Promise( resolve => resolve(f()) ) )()
.then(console.log);
console.log('next');
```
### Promise.try()
鑒于這個很常見的需求: `同步函數同步執行,異步函數異步執行` 所以現在有一個[提案](https://github.com/ljharb/proposal-promise-try),提供 `Promise.try` 方法替代上面的寫法。
```
const f = () => console.log('now');
Promise.try(f);
console.log('next');
// now
// next
```
```
const f = () => Promise.resolve('now');
Promise.try(f);
console.log('next');
// next
// now
```
事實上,`Promise.try`存在已久,Promise 庫 [`Bluebird`](http://bluebirdjs.com/docs/api/promise.try.html) [`Q`](https://github.com/kriskowal/q/wiki/API-Reference#promisefcallargs) [`when`](https://github.com/cujojs/when/blob/master/docs/api.md#whentry),早就提供了這個方法。