Promise
Origin
new Promise((resolve, reject) => { setTimeout(() => { resolve('aaa') }, 1000) }).then(res => { console.log(res, '第一层的10行处理代码');
return new Promise((resolve, reject) => { reject('err') }) }).then(res => { console.log(res, '第二层的10行处理代码');
return new Promise(resolve => { resolve(res + '222') }) }).then(res => { console.log(res, '第三层的10行处理代码'); }).catch(err => { console.log(err); })
|
new Promise(resolve => resolve(结果))简写
new Promise((resolve, reject) => { setTimeout(() => { resolve('aaa') }, 1000) }).then(res => { console.log(res, '第一层的10行处理代码');
return Promise.resolve(res + '111') }).then(res => { console.log(res, '第二层的10行处理代码');
return Promise.resolve(res + '222') }).then(res => { console.log(res, '第三层的10行处理代码'); })
|
省略掉Promise.resolve
new Promise((resolve, reject) => { setTimeout(() => { resolve('aaa') }, 1000) }).then(res => { console.log(res, '第一层的10行处理代码');
return res + '111' }).then(res => { console.log(res, '第二层的10行处理代码');
return res + '222' }).then(res => { console.log(res, '第三层的10行处理代码'); })
|
Personal some codes && throw error
new Promise((resolve,reject) => { setTimeout(() => resolve('aaa'),1000) }).then(res => { console.log('this is 1')
return new Promise((resolve) => resolve('aaa'+111)) }).then(res => console.log(res))
new Promise((resolve, reject) => { setTimeout(() => { resolve('aaa') }, 1000) }).then(res => { console.log(res, '第一层的10行处理代码');
throw 'error message' }).then(res => { console.log(res, '第二层的10行处理代码');
return Promise.resolve(res + '222') }).then(res => { console.log(res, '第三层的10行处理代码'); }).catch(err => { console.log(err); })
|
Async && Await
await 在 async 里面使用
async function my(){ setTimeout(() => console.log('my7'),1000) console.log('my8') await console.log('my1') setTimeout(() => console.log('my6'),1000) await setTimeout(() => console.log('my5'),1000) console.log('my3') await console.log('my2') await setTimeout(() => console.log('my4'),1000) return Promise.resolve('async resolve') }
my().then(res => console.log(res)).catch(err => console.log(err))
|
Result:
my8
my1
my3
my2
async resolve
Promise {: undefined}
my7
my6
my5
my4
Comprehend Deeply:https://segmentfault.com/a/1190000007535316
Execution order
Because javascript执行时单线程,则会先执行同步任务,然后再去执行任务队列(异步任务所形成的队列)中按照先进先出的顺序的任务,直到所有任务完成
So:同步任务 > 异步任务队列(async = Promise > setTimeout)(await后面的也会进入任务队列但是优先级依然大于setTimeout)
console.log('before') async function my(){ setTimeout(() => console.log('my7'),1000) console.log('my8') await console.log('my1') console.log('my3') setTimeout(() => console.log('my4'),1000) return Promise.resolve('async resolve') } console.log('after async')
my().then(res => console.log(res)).catch(err => console.log(err)) console.log('after my do')
|
Result:
before
after async
my8
my1
after my do
my3
async resolve
my7
my4
More Example:https://blog.csdn.net/weixin_43606158/article/details/91360230