简体   繁体   English

递归 function 在 Promise 中不起作用

[英]Recursive function doesn't work within Promise

I have a function which has nested Promises within it.我有一个 function ,其中嵌套了 Promise。 I want to re-execute this function when there is a length value of streamRes.length .当长度值为 streamRes.length 时,我想重新执行此streamRes.length Currently, it only executes the code and prints out the length on the console but doesn't re-execute.目前,它只执行代码并在控制台上打印出长度,但不会重新执行。

let fetchEnrolleesData = () => {
    getLastUpdatedEnrollee().then(res => {
        let params = path+"enrollees?limit=100";
        params += res.last_date ? "&last_updated_at=" + res.last_date.value : '';

        fetchEnrolleesDataInStream(res, params).then(streamRes => {
            if(streamRes.length) {
                console.log(streamRes.length);
                fetchEnrolleesData();
            }
        });
    });
}

As evolutionxbox wrote , you need to return the promise returned by getLastUpdatedEnrollee as well as the promise getLastUpdatedEnrollee itself.正如Evolutionxbox 所写,您需要返回 getLastUpdatedEnrollee 返回的getLastUpdatedEnrollee以及 promise getLastUpdatedEnrollee本身。 In general, when calling a promise within a function, you need to return those promises in order to use those values outside of that function.通常,当在 function 中调用 promise 时,您需要返回这些承诺,以便在 function 之外使用这些值。

Here is your code with return added as needed:这是您的代码,并根据需要添加了return

let fetchEnrolleesData = () => {
    return getLastUpdatedEnrollee().then(res => {
        let params = path+"enrollees?limit=100";
        params += res.last_date ? "&last_updated_at=" + res.last_date.value : '';

        return fetchEnrolleesDataInStream(res, params).then(streamRes => {
            if(streamRes.length) {
                console.log(streamRes.length);
                return fetchEnrolleesData();
            }
        });
    });
}

As an optional side note, you may or may not prefer to use () => … syntax instead of () => { … } to remove the need to write return in the top-level function.作为可选的附注,您可能更喜欢使用() => …语法而不是() => { … }来消除在顶级 function 中编写return的需要。 You can do that in the top-level function because it has no other statements;您可以在顶级 function 中执行此操作,因为它没有其他语句; this wouldn't work in the inner function, which has multiple statements.这在具有多个语句的内部 function 中不起作用。 See arrow function expressions for more detail.有关更多详细信息,请参见箭头 function 表达式

let fetchEnrolleesData = () =>
    getLastUpdatedEnrollee().then(res => {
        // …
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM