我想創建一個可以同時處理異步/等待和常用回調模式的函數。所以像下面將工作:如何使功能與await一起工作,但也可以採取回調?
function myFunc(cb) {
setTimeout(function(){ //something async
console.log('hello');
cb();
});
}
myFunc(function(){
console.log('world');
});
,但下面是什麼都不行
function myFunc(cb = function(){}) {
setTimeout(function(){ //something async
console.log('hello');
cb();
}, 1000);
}
(async()=> {
await myFunc();
console.log('world');
})();
我理解await
工作myFunc
需要返回一個承諾,即使我一些想法考慮如何回調和回覆承諾,我希望看到一些正確的方法來做到這一點。
通常,當我看到這在庫中,函數採用2個參數與所述第二個是回調,如果該參數是omitte d,它會返回一個承諾。 – agm1984