ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## 区分同步代码和异步代码 在实际开发中,使用 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),早就提供了这个方法。