const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/user', { useNewUrlParser: true });
const model = mongoose.model('user', mongoose.Schema({
username: { type: String },
password: { type: String },
user_ssh: { type: String }
}, { collection: "user", versionKey: false, strict: true }));
const ping_1 = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve("1");
}, 1000);
//model.findOne({ username: "1" }, (error, doc) => resolve({ error: error, doc: doc }));
});
};
const ping_2 = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve("2");
}, 2000);
//model.findOne({ username: "2" }, (error, doc) => resolve({ error: error, doc: doc }));
});
};
const ping_3 = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve("3");
}, 3000);
//model.findOne({ username: "3" }, (error, doc) => resolve({ error: error, doc: doc }));
});
};
const ping_4 = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve("4");
}, 4000);
//model.findOne({ username: "4" }, (error, doc) => resolve({ error: error, doc: doc }));
});
};
const ping_5 = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve("5");
}, 5000);
//model.findOne({ username: "5" }, (error, doc) => resolve({ error: error, doc: doc }));
});
};
const ping_6 = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve("6");
}, 6000);
// model.findOne({ username: "6" }, (error, doc) => resolve({ error: error, doc: doc }));
});
};
ping_1() //promise链式调用开始
.then((data) => {
console.log(data);
return ping_2();
}).then((data) => {
console.log(data);
return ping_3();
}).then(data => {
console.log(data);
return ping_4();
}).then(data => {
console.log(data);
return ping_5();
}).then(data => {
console.log(data);
return ping_6();
}).then((data) => {
console.log(data)
});
console.log("================================");
console.time("time");
Promise.all( //promise.all 集中并行处理
[
ping_1(),
ping_2(),
ping_3(),
ping_4(),
ping_5(),
ping_6()
]
).then((data) => {
console.timeEnd("time");
console.log(data);
});
可以发现,使用promise链式调用的时长耗费了21秒,而用promise.all则仅仅只有6秒