我知道承诺是我问题的答案,但需要有关如何在我的情况下使用的帮助。
我的代码是:
...
invoke: (abc) => {
module.exports.getData();
return;
},
getData: () => {
request(options, function(err, res, body) {
if (res && (res.statusCode === 200 || res.statusCode === 201)) {
logger.info("vacation balacne response:" + body);
}
});
},
...
因此,在我目前的情况下,调用方法不会等待getData完成。我需要从 getData 中的调用返回响应数据,并在调用方法中使用它。请指教。
当然不会,它是一个异步函数。最简单的解决方案是将该回调从getData
移动到invoke
,以便调用可以将其传递给getData,一旦数据可用,getData就可以调用"您需要继续发生的任何事情":
var Thing = {
....
invoke: (andThenDoThis) => {
Thing.getData(andThenDoThis);
},
getData: (andThenDoThis) => {
request(options, function(err, res, body) {
if (res && (res.statusCode === 200 || res.statusCode === 201)) {
logger.info("vacation balacne response:" + body);
}
// THIS IS WHERE YOUR CODE WILL NOW CONTINUE:
if (andThenDoThis) {
andThenDoThis(err, res, body)
}
});
},
...
};
虽然这当然是愚蠢的,因为只需定义一个引用的对象this
:
class Thing {
constructor(options) {
this.options = options;
}
invoke() {
this.getData((err, res, body) => {
this.handleData(err, res, body);
});
}
getData(andThenDoThis) {
request(this.options, (err, res, body) => {
this.handleData(err, res, body)
});
}
handleData(err, res, body) {
// do some `err` checking
// do some `res` checking
// do some `body` parsing
// do whatever else
if (this.options.forwardData) {
this.options.forwardData(...);
}
}
...
}
然后做这些事情之一:
// make a thing:
let thing = new Thing({
...,
forwardData: (data) => {
// do whatever with your data.
},
...
});
// and then invoke whatever it is you actually needed to do.
thing.invoke();
// code here keeps running, but that's fine, because now you're
// using "code triggers only when, and where, it needs to".