We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
function getResult(result, val) { val && result.push(val) return result } const pushResult = getResult.bind(null, []) const chainResult = getResult.bind(null, []) const orderResult = getResult.bind(null, []) function task(idx, type) { return new Promise((resolve, reject) => { setTimeout(() => { const num = idx + 1 resolve(num) // console.log(`${type}: ${num}`) }, Math.random() * 2000) }) } function generatorFn(num, type) { // 返回一个包含了5个task的数组,每个task都会返回一个Promise对象 return Array.from(new Array(num)).map((item, idx) => task.bind(null, idx, type)) } // Promise.all来执行task list Promise.all(generatorFn(5, 'all').map(fn => fn().then(pushResult))).then(result => console.log('all: ', pushResult())) // 随机 const taskFn = generatorFn(5, 'all') // 按顺序执行task Promise.resolve() .then(taskFn[0]) .then(chainResult) .then(taskFn[1]) .then(chainResult) .then(taskFn[2]) .then(chainResult) .then(taskFn[4]) .then(chainResult) .then(result => console.log('chain: ', chainResult())) // [1,2,3,5] // 利用reduce来按顺序执行task list const order = generatorFn(5, 'order').reduce((promise, cur) => { return promise.then(cur).then(orderResult) }, Promise.resolve()) order.then(res => console.log('order: ', orderResult())) // order: [1, 2, 3, 4, 5]
Promise顺序执行可以手动编写then,也可以利用for循环去调用then执行,for循环可转变为reduce实现
The text was updated successfully, but these errors were encountered:
No branches or pull requests
Promise顺序执行可以手动编写then,也可以利用for循环去调用then执行,for循环可转变为reduce实现
The text was updated successfully, but these errors were encountered: