Skip to content

ES6中的Promise #54

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

Open
alanhe421 opened this issue May 21, 2018 · 5 comments
Open

ES6中的Promise #54

alanhe421 opened this issue May 21, 2018 · 5 comments

Comments

@alanhe421
Copy link
Owner

alanhe421 commented May 21, 2018

Promise的作用是解决回调金字塔的问题

function myAsyncFunction(url) {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.open("GET", url);
            xhr.onload = () => resolve(xhr.responseText);
            xhr.onerror = () => reject(xhr.statusText);
            xhr.send();
        });
    }

    myAsyncFunction("a.json").then(function (value) {
        console.log(value);
    })
@alanhe421
Copy link
Owner Author

alanhe421 commented May 28, 2018

Promise的链式调用及中止

如下为3个方法连续执行

var firstMethod = function () {
        return new Promise(function (resolve, reject) {
            console.log('first method completed');
            resolve({data: 'firstMethod-ERROR'});
        });
    };


    var secondMethod = function (someStuff) {
        return new Promise(function (resolve, reject) {
            console.log('second method completed');
            resolve({data: "secondMethod-ERROR"});
        });
    };

    var thirdMethod = function (someStuff) {
        return new Promise(function (resolve, reject) {
            console.log('third method completed');
            resolve({data: "thirdMethod-ERROR"});
        });
    };

    firstMethod()
        .then(secondMethod).then(thirdMethod).catch((res) => {
        console.log("catch");
        console.log(res);
    });

输出结果为:
image

第一个方法异常,promise链中止

 var firstMethod = function () {
        return new Promise(function (resolve, reject) {
            console.log('first method completed');
            reject({data: 'firstMethod-ERROR'});
        });
    };


    var secondMethod = function (someStuff) {
        return new Promise(function (resolve, reject) {
            console.log('second method completed');
            resolve({data: "secondMethod-ERROR"});
        });
    };

    var thirdMethod = function (someStuff) {
        return new Promise(function (resolve, reject) {
            console.log('third method completed');
            resolve({data: "thirdMethod-ERROR"});
        });
    };

    firstMethod()
        .then(secondMethod).then(thirdMethod).catch((res) => {
        console.log("catch");
        console.log(res);
    });

输出结果为:
image

相关文档

@alanhe421 alanhe421 added the ES6 label Jul 25, 2018
@alanhe421
Copy link
Owner Author

一个问题

  function myPromiseRace(arr) {
        return new Promise((resolve, reject) => {
          for (let item of arr) {
            item.then(
              (res) => {
                resolve(res);
              },
              (err) => {
                reject(err);
              }
            );
          }
        });
      }
      function myPromiseRace2(arr) {
        return new Promise((resolve, reject) => {
          for (let item of arr) {
            item
              .then((res) => {
                resolve(res);
              })
              .catch((err) => {
                reject(err);
              });
          }
        });
      }

      let p1 = Promise.reject(1),
        p2 = Promise.resolve(2),
        p3 = Promise.resolve(3);

      myPromiseRace([p1, p2, p3])
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });

      myPromiseRace2([p1, p2, p3])
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });

@alanhe421
Copy link
Owner Author

Primise.all实现

function promiseAll(promiseBs = []) {
  return new Promise(function (resolve) {
    let resArr = [];
    for (let index = 0; index < promiseBs.length; index++) {
      promiseBs[index].then(function (res) {
        resArr[index] = res;
        if (resArr.filter(Boolean).length === promiseBs.length) {
          resolve(resArr);
        }
      });
    }
  });
}

promiseAll([
  Promise.resolve(11111),
  Promise.resolve(1),
  Promise.resolve(11),
  Promise.resolve(111),
  Promise.resolve(1111),
]).then((res) => {
  console.log(res);
});

@alanhe421
Copy link
Owner Author

原型

Promise.all2 = function (promises) {
  return new Promise((resolve) => {
    let arr = new Array(promises.length);
    let count = 0;
    promises.forEach((p, index) => {
      p.then((res) => {
        ++count;
        arr[index] = res;
        if (count == arr.length) {
          resolve(arr);
        }
      });
    });
  });
};

const p = Promise.all2([
  Promise.resolve(1),
  Promise.resolve(11),
  Promise.resolve(1111)
]).then((res) => console.log(res));

@alanhe421
Copy link
Owner Author

var date = new Date() 

console.log(1, new Date() - date) 

setTimeout(() => {
    console.log(2, new Date() - date)
}, 500) 

Promise.resolve().then(console.log(3, new Date() - date)) 

while(new Date() - date < 1000) {} 

console.log(4, new Date() - date)

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

No branches or pull requests

1 participant