我为这个问题的新意而道歉。我是一名经验丰富的程序员,但我是javascript的新手。因此,我可能会使用不正确的术语。
我正在尝试编写自己的中间件处理程序(作为练习以更好地理解异步方法)。我使用名为somethingsDone
的名为app
的成员函数作为回调传递给外部调用者。当客户端调用somethingsDone
时,其中this
的值未定义。这是代码:
#!/usr/bin/env node
"use strict"
var YAML = require('js-yaml')
var fs = require('fs')
var app = {
cb_index: 0,
callbacks: [],
finished_callback: null,
use (fn) {
this.callbacks.push(fn)
},
somethingsDone(req) {
debugger
// the callback at index this.cb_index is done
if (this.cb_index == this.callback.count -1) {
this.finished_callback(req)
}
this.cb_index += 1
this.callbacks[this.cb_index]()
},
run (req, done) {
this.finished_callback = done
this.callbacks[0](req, this.somethingsDone)
}
}
app.use((req, next) => {
fs.readFile(req.filepath, (err, data) => {
console.log(`Loaded file data from ${req.filepath}: ${data}`)
req.contents = data
next()
})
})
app.use((req, next) => {
setTimeout(2, () => {
console.log('Dumping YAML')
req.yaml = YAML.safeDump(input)
next()
})
})
app.use((req, next) => {
console.log(`YAML data is:\n${req.yaml}`)
})
app.run({ filepath: "/home/ben/docker-compose.json"}, (req) => {
console.log(`Hey we're finished! Request data is:\n${req}`)
})
失败并出现此错误:
/home/ben/js-learning/middleware.js:20
if (this.cb_index == this.callback.count -1) {
^
TypeError: Cannot read property 'cb_index' of undefined
at somethingsDone (/home/ben/js-learning/middleware.js:20:13)
at /home/ben/js-learning/middleware.js:37:5
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:380:3)
我已经尝试使用谷歌搜索和阅读如何在javascript中设置this
,但我甚至不确定如何搜索(我甚至不知道在javascript中调用了什么)。
我做错了什么?如何在调用回调时正确定义this
?