我有异步递归函数,需要一些时间来执行。
请参阅以下两个功能
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
。
请给我一个克服这个问题的建议。
谢谢
您可以将整个事物视为火车(承诺火车)以及您想要在火车中称为货车的功能。您所要做的就是按正确的顺序连接它们。
有两种方式将货车连接到火车上。一种是通过回应承诺的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);