# 多异步协作

# 异步操作

我们通过定义一个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);
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 哨兵变量

var after = function(times, callback) {
    var count = 0,res = {};
    return function(key, val) {
        res[key] = val;
        count ++;
        if(count == times) {
            callback(res);
        }
    }
}
1
2
3
4
5
6
7
8
9
10

# 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);
});
1
2
3
4
5
6
7
8
9
10
11
12
13

# 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);
            });
        }
    });
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
更新于: 7/8/2020, 7:46:15 AM