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

Promise串行 #152

Open
Sunny-117 opened this issue Nov 3, 2022 · 4 comments
Open

Promise串行 #152

Sunny-117 opened this issue Nov 3, 2022 · 4 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@ouyangbo123
Copy link

Promise+async+await

@Banks1y
Copy link

Banks1y commented Jun 17, 2023

//Promise串行
async function serialPromise(taskarr) {
  let res = [];
  for (const task of taskarr) {
    try {
      res.push(await task());
    } catch (err) {
      res.push(null);
    }
  }
  return res;
}

@bobocomeon
Copy link

bobocomeon commented Oct 15, 2023

// 使用reduce

function runPromiseByQueue(myPromises) {
  return myPromises.reduce((prev, next) => {
    return prev.then(() => next());
  }, Promise.resolve());
}
const createPromise = (time, id) => () => new Promise(resolve => {
  setTimeout(() => {
    resolve(time);
    console.log("promise", id);
  }, time);
});
runPromiseByQueue().then((res) => {
  console.log(res);
});

@tyust512
Copy link

function promiseSerial(promises) {
  let result = Promise.resolve()
  // console.log(promises)
  promises.forEach(promise => {
    // console.log(promise)
    result = result.then(() => promise)
  })
}

const promises = new Array(4).fill().map((item, index) => {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log(index)
      resolve()
    }, 2000 * index * Math.random())
  })
})

// console.log(typeof promises[0])

promiseSerial(promises)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants