我试图理解javascript(typescript)中的回调机制。如果我有一个需要回调作为输入参数的函数,我是否必须显式使用 return 语句将其与调用代码中的实际回调实现 Hook ,或者我们可以简单地在被调用的代码中使用“回调”引用它会自动与调用代码中的回调代码 Hook
代码示例( typescript )
// callback code being hooked up using return statement
clear(collectionName: string, callback: any) {
this.getConnection((err, db) => {
if (!db)
return callback(err, null);
db.collection(collectionName).remove();
});
return callback();
}
// callback code being hooked up using reference to reserved callback keyword for automatic hook up with calling code
clear(collectionName: string, callback: any) {
this.getConnection((err, db) => {
if (!db)
return callback(err, null);
db.collection(collectionName).remove({}, callback);
});
}
最佳答案
你不需要返回,你可以简单地调用它,就像
clear(collectionName: string, callback: any) {
this.getConnection((err, db) => {
if (!db)
callback(err, null);
db.collection(collectionName).remove();
});
return callback();
}
// callback code being hooked up using reference to reserved callback keyword for automatic hook up with calling code
clear(collectionName: string, callback: any) {
this.getConnection((err, db) => {
if (!db)
callback(err, null);
db.collection(collectionName).remove({}, callback);
});
}
关于javascript - Javascript中的回调机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45814724/