Skip to content
New issue

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

2020/03/31 Promise 顺序执行 #39

Open
ChenPt opened this issue Mar 31, 2020 · 0 comments
Open

2020/03/31 Promise 顺序执行 #39

ChenPt opened this issue Mar 31, 2020 · 0 comments
Labels

Comments

@ChenPt
Copy link
Owner

ChenPt commented Mar 31, 2020

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实现

@ChenPt ChenPt added the ES6 label Apr 1, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant