npm init 把普通的项目目录变成npm包
npm install glob 安装glob依赖,项目转移时可以把node_modules删除后再转移
rm -rf node_modules 删除node_modules
npm install 读取项目中package.json中的依赖目录,安装node_modules
02ebe99b08a04d78a0675be2ba047ca.png
// 回调函数
function interview(callback){
setTimeout(()=>{
var num=Math.random();
console.log(num);
if(num<0.5){
callback('succ')
}else{
callback(new Error('fail'))
}
},500)
}
try{
interview(function(res){
if(res instanceof Error){
return console.log('cry');
}
console.log('smile')
})
}catch{
}
5557df102a2074a1759b0e2be9125c1.png
9d4480403c708626d2d0ece2d27b262.png
//Promise
//例一
function interview() {
return new Promise((resolve, reject) => {
setTimeout(() => {
var num = Math.random();
console.log(num);
if (num < 0.5) {
resolve('succ')
} else {
reject(new Error('fail'))
}
}, 1000)
})
}
var promise = interview();
promise.then(
(res) => {
console.log('smile')
}
).catch(
(err) => {
console.log('cry')
}
)
//Promise
//例二
function interview(round) {
return new Promise((resolve, reject) => {
setTimeout(() => {
var num = Math.random();
console.log(num);
if (num < 0.5) {
resolve('succ')
} else {
var error=new Error('fail');
error.round=round;
reject(error);
}
}, 1000)
})
}
var promise=interview(1)
.then(()=>{
return interview(2)
})
.then(()=>{
return interview(3)
})
.then(()=>{
console.log('smile');
})
.catch((err)=>{
console.log('cry at '+err.round+' round')
})
//Promise
//例三
function interview(name) {
return new Promise((resolve, reject) => {
setTimeout(() => {
var num = Math.random();
console.log(num);
if (num < 0.5) {
resolve('succ')
} else {
var error = new Error('fail');
error.name = name;
reject(error);
}
}, 1000)
})
}
Promise.all([
interview('geekbang'),
interview('tencent')
]).then(() => {
console.log('smile');
})
.catch((err) => {
console.log('cry at ' + err.name)
})
4509f64058875aa82394038bbaa8fb6.png
//async、await
function interview(round) {
return new Promise((resolve, reject) => {
setTimeout(() => {
var num = Math.random();
console.log(num);
if (num < 0.5) {
resolve('succ')
} else {
var error=new Error('fail');
error.round=round;
reject(error);
}
}, 1000)
})
}
(async function(){
try{
// await interview(1);
// await interview(2);
// await interview(3);
await Promise.all([interview(1),interview(2)])
}catch(e){
return console.log('cry at '+e.round+' round');
}
console.log('smile');
})()
网友评论