我想了一會兒,想出一個從異步瀑布(異步庫)函數中抽象函數(讓我的代碼保持乾爽)的好方案,但是我一直收到錯誤說沒有定義cb
。此外,在傳遞this
至bind
時,async
定義的功能是範圍,並且也通過cb
。最終,我找到了一個可行的解決方案(將cb
作爲函數添加到this
對象中),但它看起來有點混亂,可能有更好的方法。有什麼建議?:當使用異步瀑布時綁定回調函數
// registerController.js
const async = require('async');
const registerService = require('../services/register');
// Api endpoint code
...
// is there a better way than (this.cb = cb)
let callbackHandler = (err, res) => {
if (err) this.cb(err);
this.cb(null, res);
};
// asynchronously perform registration
async.waterfall([
(cb) => {
registerService.createAccount(username, email, callbackHandler.bind(this.cb = cb));
},
(res, cb) => {
registerService.doSomethingElse(domain, callbackHandler.bind(this.cb = cb);
},
....
// registerService.js
module.exports = {
createAccount: (username, email, callback) => {
httpService.request({
host: myHost,
method: 'POST',
path: '/api/signup',
body: {
username,
email
}
}).then((res) => {
return callback(null, res);
}).catch((err) => {
return callback(err);
});
},
...
}
注:重構到服務文件進行單元測試的目的和精益控制器(服用MVC方式)代碼
這是bollocks,這是行不通的。如果有的話,你可能想要做'callbackHandler.bind({cb:cb})' – Bergi
@Bergi它確實有效,因爲我試過了,我會嘗試你的解決方案,儘管 – timhc22