我有异步递归函数,需要一些时间来执行。
参见以下两个功能
public sendAndRecivesMessage(content:string, finalMessage:Message, outMessageCount:number = 1){
this.promise = new Promise((resolve, reject) => {
this.doSendAndRecivesMessage(content, finalMessage, outMessageCount);
console.log("Have to wait until above function finish executing");
resolve (finalMessage);
});
return this.promise;
}
private doSendAndRecivesMessage(content:string, finalMessage:Message, outMessageCount:number = 1){
let newContent = IREDMART_KEYWORD + APP_IDENTITY + outMessageCount + " " + content;
let message:Message = new Message(newContent, API_END_POINT);
this.sendMessage(message);
let promise = this.recieveMessage();
promise.then((message) => {
let inMessageCount:number = message.content.split(MSG_COUNT_SEPARATOR)[1];
finalMessage.content += message.content.split(MSG_COUNT_SEPARATOR)[2];
if(inMessageCount == 1){
finalMessage.reciever = message.reciever;
finalMessage.date = message.date;
}
else{
this.sendAndRecivesMessage(content, finalMessage, outMessageCount + 1);
}
});
}
这里doSendAndRecivesMessage
函数需要一些时间来执行,它是一个递归函数。
sendAndRecivesMessage
函数中的我需要等到上面的函数完成执行并且必须返回finalMessage
我该如何实现这个目标?
另外,我尝试了如下
public sendAndRecivesMessage(content:string, finalMessage:Message, outMessageCount:number = 1){
let newContent = IREDMART_KEYWORD + APP_IDENTITY + outMessageCount + " " + content;
let message:Message = new Message(newContent, API_END_POINT);
this.promise = new Promise((resolve, reject) => {
this.sendMessage(message);
let promise = this.recieveMessage();
promise.then((message) => {
let inMessageCount:number = message.content.split(MSG_COUNT_SEPARATOR)[1];
finalMessage.content += message.content.split(MSG_COUNT_SEPARATOR)[2];
if(inMessageCount == 1){
finalMessage.reciever = message.reciever;
finalMessage.date = message.date;
resolve(finalMessage);
}
else{
this.sendAndRecivesMessage(content, finalMessage, outMessageCount + 1);
}
});
});
return this.promise;
}
但由于函数是异步和递归的,因此返回promise不包含已解析的finalMessage
。
请给我一个克服这个问题的建议。
由于
答案 0 :(得分:1)
您可以将整个事物视为火车(承诺列车)以及您想要在火车中作为货车的功能。您所要做的就是按正确的顺序连接它们。
有两种方式将货车连接到火车上。一种是通过回传承诺的then
函数。第二个是在其中一个回调中返回另一个承诺。
以下是您可以如何构建代码的示例:
function randomNumber() {
// a function that can later return a value
return Promise.resolve(Math.random());
}
// recursive function, keeps calling itself until the condition is met
function collectValues(until, previous) {
// call the async function return a promise
return randomNumber().then((value) => {
// when we get a number we check the condition
console.log(`prev:${previous} new:${value}`);
let result = previous + value;
if (result > until) {
// when satisfied just return the final message
return result;
} else {
// return the promise from the next recursive call with new params
return collectValues(until, result);
}
});
}
collectValues(5, 0).then(console.log);