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

多异步协作 #16

Open
Clearives opened this issue Apr 28, 2019 · 0 comments
Open

多异步协作 #16

Clearives opened this issue Apr 28, 2019 · 0 comments
Labels

Comments

@Clearives
Copy link
Owner

多异步协作

异步操作

我们通过定义一个count来监听,当所有的异步返回时,我们统一处理res。

let count = 0;
let res = {};
const done = function(key, val) {
    res[key] = val;
    count ++;
    if(count === 3) {
        render(res);
    }
};
fs.readFile(template_path, 'utf8', (err, tp) => {
    done('tp', tp);
}); 
db.query(sql, (err, data) => {
    done('data', data);
});
$.get(demo.json, (err, res) => {
    done('res', res);
});

哨兵变量

var after = function(times, callback) {
    var count = 0,res = {};
    return function(key, val) {
        res[key] = val;
        count ++;
        if(count == times) {
            callback(res);
        }
    }
}

Promise.all使用

let promise1 = new Promise(function (resolve) {
    resolve(1);
});
let promise2 = new Promise(function (resolve) {
    resolve(2);
});
let promise3 = new Promise(function (resolve) {
    resolve(3);
});

Promise.all([promise1, promise2, promise3]).then(function (res) {
    console.log(res);
});

Promise.all自己实现

Promise.prototype.all = function (promises) {
    let results = [];
    let promiseCount = 0;
    let promisesLength = promises.length;
    return new Promise(function (resolve, reject) {
        for (let val of promises) {
            Promise.resolve(val).then(function (res) {
                promiseCount++;
                results[i] = res;
                if (promiseCount === promisesLength) {
                    return resolve(results);
                }
            }, function (err) {
                return reject(err);
            });
        }
    });
};
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