一些复杂的表单提交,会涉及到下个选择框的值来自前几个入参值请求 API 所得(几个入参值是接口返回得出参),这种情况下,就满足多个 Promise 顺序执行。
解决
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const f1 = () => new Promise((resolve, reject) => { setTimeout(() => { console.log('p1 running') resolve(1) }, 1000) })
const f2 = () => new Promise((resolve, reject) => { setTimeout(() => { console.log('p2 running') resolve(2) }, 500) })
|
Promise 回调
1 2 3
| f1().then(() => { f2() })
|
async 函数
1 2 3 4
| !(async function asyncPromise() { await f1() f2() })()
|
reduce
1 2 3 4
| const arr = [f1, f2] const runPromiseInsequence = (array, value) => array.reduce((promiseChain, currentFunction) => promiseChain.then(currentFunction), Promise.resolve(value)) runPromiseInsequence(arr, 'init')
|
递归
1 2 3 4 5 6 7 8 9 10
| const arr = [f1, f2] function sequencePromise(arr) { const pro = arr.shift() if (pro) { pro().then(() => { sequencePromise(arr) }) } } sequencePromise(arr)
|
forEach
1 2 3 4 5 6 7 8 9
| const arr = [f1, f2]
function func(arr) { let res = Promise.resolve() arr.forEach((item) => { res = res.then(item) }) } func(arr)
|