jiaochunxiao / fe-blog

好好学习,天天向上
1 stars 1 forks source link

异步Promise的顺序执行 #15

Open jiaochunxiao opened 4 years ago

jiaochunxiao commented 4 years ago

给定p1, p2, p3,实现一个方法依次输出 1,2, 3, done

var p1 =  function() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(1);
    }, 1000);
  })
}
var p2 =  function() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(2);
    }, 1000);
  })
}
var p3 =  function() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(3);
    }, 1000);
  })
}

function excutePromise(arr) {
  let p = Promise.resolve();
  arr.forEach(item => {
    p = p.then(item).then(data => {
      console.log(data);
    });
  })
  return p;
}
excutePromise([p1, p2, p3]).then(() => {
  console.log('done');
});
jiangzhenxiang commented 4 years ago
// 给定p1, p2, p3,实现一个方法依次输出 1,2, 3, done

var p1 = function () {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(1);
        }, 1000);
    })
}
var p2 = function () {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(2);
        }, 1000);
    })
}
var p3 = function () {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(3);
        }, 1000);
    })
}

async function fn(arr) {
    for (let index = 0; index < arr.length; index++) {
        console.log(await arr[index]());
    }
}
fn([p1,p2,p3]).then(() => {console.log('done1')});
jiangzhenxiang commented 4 years ago
function createQueue(tasks) {
            return new Promise(async (resolve, reject) => {
                for (let i = 0; i < tasks.length; i++) {
                    await tasks[i]();
                }

                resolve('done');
            })
        }