【发布时间】:2019-05-27 21:32:43
【问题描述】:
我正在编写一个简单的递归函数,它调用一个函数driver,它返回一个承诺。我的 aaa 函数必须在调用结束时返回一个 Promise。
所以这段代码是我的问题的简化:
代码:
function aaa(index) {
driver(index)
.then(index => {
if (index < 100)
aaa(index);
else
console.log('finito' + index);
})
}
function driver(index) {
return new Promise(resolve => {
resolve(index + 1);
});
}
aaa(0);
我的解决方案:
function aaa(index) {
console.log(index);
return Promise.resolve(index)
.then((index) => {
driver(index)
.then( index => {
if (index < 100)
return aaa(index);
else
return Promise.resolve(index);
});
});
}
function driver(index) {
return new Promise(resolve => {
resolve(index + 1);
});
}
function doTheThing() {
Promise.resolve(0).then(aaa)
.then(()=>{
alert('end');
});
}
doTheThing();
但我在aaa 函数的最后一个then 中仍然有一个编辑器警告,即:
Argument of type '(index: {}) => Promise<void> | Promise<{}>'
is not assignable to parameter of type '(value: {}) => void | PromiseLike<void>'.
Type 'Promise<void> | Promise<{}>' is not assignable to type 'void | PromiseLike<void>'.
Type 'Promise<{}>' is not assignable to type 'void | PromiseLike<void>'.
【问题讨论】:
-
哦哦不!!!谁不喜欢我的问题!!!解释为什么!!!!!!
-
首先你的问题是什么?乍一看'aaa'是无效函数,所以你不能调用aaa(0)。然后......
-
我想将其转换为返回承诺的异步函数
-
我要等到这个函数结束才能执行一些代码!!!我被屏蔽了!
-
我不确定您对此有何期望,但是...将解析函数作为递归传递,不要再次调用驱动器...
标签: typescript recursion promise es6-promise