嗨,我已经编写了此功能。
GetIndex方法
getIndex(req: connreq){
var found = false;
var number =0;
this.firereq.child(req.recipient).once('value', function(snapshot) {
if (!snapshot.exists()) {
console.log('Not exists');
this.x = '0';
}
});
}
在这个函数中,我称之为它。
SendCommand方法
async sendcommand(req: connreq, cmd: string) {
this.getIndex(req);
var promise = new Promise((resolve, reject) => {
this.firereq
.child(req.recipient)
.child(this.x) .set({
sender: req.sender,
Command: cmd,
})
.then(() => {
resolve({ success: true });
})
.catch(err => {
resolve(err);
});
});
return promise;
}
但是,第二个函数似乎在getIndex方法完成之前就继续执行。我假设我们可以使用awaits和promises来强制sendcommand函数在完成其余任务之前等待Getindex完成。任何帮助将不胜感激
答案 0 :(得分:1)
在getIndex()方法中返回一个promise,然后在中执行第二个,然后进行回调。因此,通常,getIndex应该是:
getIndex(req: connreq){
return new Promise((resolve,reject) =>
{
var found = false;
var number =0;
this.firereq.child(req.recipient).once('value',
function(snapshot) {
if (!snapshot.exists()) {
console.log('Not exists');
this.x = '0';
reject('Not exists');
}
resolve('exists');
});
});
}
如果找不到,上述内容将触发catch块,如果找到则将触发then块:
this.getIndex(req)
.then(() => {
this.firereq
.child(req.recipient)
.child(this.x) .set({
sender: req.sender,
Command: cmd,
})
.then(() => {
resolve({ success: true });
})
.catch(err => {
resolve(err);
})
})
.catch(err => {
resolve(err);
});
答案 1 :(得分:1)
在第一个功能中,请执行以下操作:
getIndex(req: connreq){
return new Promise((resolve, reject) =>
let found = false;
let number =0;
this.firereq.child(req.recipient).once('value', function(snapshot) {
if (!snapshot.exists()) {
reject("not exists");
console.log('Not exists');
this.x = '0';
}
else{
resolve(snapshot.val());
}
});
});
}
那么您可以做:
async sendcommand(req: connreq, cmd: string) {
this.getIndex(req).then((data)=>
{
var promise = new Promise((resolve, reject) => {
this.firereq
.child(req.recipient)
.child(this.x) .set({
sender: req.sender,
Command: cmd,
})
.then(() => {
resolve({ success: true });
})
.catch(err => {
resolve(err);
});
});
});
return promise;
}
通过这种方式,getIndex()
将返回一个诺言,并且then()
返回之后将执行所有insde getIndex()
。
答案 2 :(得分:1)
从Promise
返回getIndex
,并在await
函数中返回sendCommand
getIndex(req: connreq){
return new Promise((resolve, reject) => {
var found = false;
var number =0;
this.firereq.child(req.recipient).once('value', function(snapshot) {
if (!snapshot.exists()) {
console.log('Not exists');
this.x = '0';
}
});
resolve();
}
});
和
async sendcommand(req: connreq, cmd: string) {
await this.getIndex();
....
}