function cbFun() {
console.log("hello word!");
}
function asyncFun(callback) {
setTimeout(() => {
callback();
}, 3000);
}
asyncFun(cbFun);
function cbFun() {
console.log("hello word!");
}
function asyncFun() {
setTimeout(() => {
emitter.emit("msg");
}, 3000);
}
var emitter = new EventEmitter3();
emitter.on("msg", cbFun);
// 執行異步函數
asyncFun()
var PubSub = function() {
this.list = {};
};
//給訂閱者提供訂閱的方法
PubSub.prototype.subscribe = function(key, callback) {
if (!this.list[key]) {
this.list[key] = [];
}
this.list[key].push(callback);
};
//發佈消息的功能
PubSub.prototype.publish = function(key, args) {
var fns = this.list[key];
// 若是沒有訂閱過該消息的話,則返回
if (!fns || fns.length === 0) {
return;
}
var len = fns.length;
while (len--) {
fns[len].apply(this, args);
}
};
// 取消訂閱
PubSub.prototype.unsubscribe = function(key, fn) {
var fns = this.list[key];
if (!fns || fns.length === 0) {
return false;
}
if (!fn) {
fns && (fns.length = 0);
} else {
// 將fn刪除
var len = fns.length;
while (len--) {
if (fns[len] === fn) {
fns.splice(len, 1);
}
}
}
};
var pubsub = new PubSub();
pubsub.subscribe("msg", cbFun);
function cbFun() {
console.log("hello word!");
}
function asyncFun() {
setTimeout(() => {
pubsub.publish("msg");
}, 3000);
}
asyncFun();
function cbFun() {
console.log("hello word!");
}
function asyncFun(callback) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 3000);
});
}
asyncFun().then(()=>{
cbFun()
})
function cbFun() {
console.log("hello word!");
}
function asyncFun() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 3000);
});
}
async function asyncFunArr() {
await asyncFun();
cbFun();
}
asyncFunArr();
參考:javascript