函数过早返回过滤器并降低了效果 [英] function returning too early before filter and reduce finish

查看:86
本文介绍了函数过早返回过滤器并降低了效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下功能,应该检查一个数组,求和一些值,然后返回一个总和的字符串(对于Dialogflow / Google助手):

I have the following function, which is supposed to check through an array, sum up some values and then return a string with the sum (for Dialogflow/Google Assitant):

function howMuch(app) {
return bank.getTurnovers(accessToken)
    .then((result) => {
        const { turnovers } = JSON.parse(result);

        let sum = turnovers
            .filter((i) => {
                if (i.tags.includes(tag)) {
                    console.log(i); // correctly prints relevant elements
                    return i;
                }
            })
            .reduce((prev, j) => {
                console.log(prev, j.amount) // correctly prints 0 7, 7 23
                return prev + j.amount;
            }, 0);

        console.log(sum); // prints sum correctly: 30
        return app.ask('You have spend ' + sum); // returns 0 for sum
    })
    .catch((error) => {
        // handle error
    });
};

但是问题是,该函数仅返回您已花费0 ,其中0是reduce函数中设置的初始值,但总和实际上为30。它似乎并不等待reduce完成。
这是什么问题?

The problem is however, the function only returns You have spend 0, where 0 is the initial value set in the reduce function, but the sum is actually 30. It just does not seem to wait for the reduce to finish. What is the problem here?

推荐答案

app.ask()将响应发送回用户(并且,因为您使用的是 ask()而不是 tell(),也表示保持麦克风打开)。它完全返回Express的 Response.send()方法返回的内容。

app.ask() sends the response back to the user (and, since you're using ask() and not tell(), also says to keep the microphone open). It returns exactly what Express' Response.send() method returns.

将字符串返回到调用函数。

It does not return the string to the calling function.

如果需要该值,则不应调用 app.ask()此时。只需返回值(或最终会解决该值的Promise),然后调用 app.ask()

If you want the value, you shouldn't call app.ask() at this point. Just return the value (or a Promise that eventually resolves to that value) and have that call app.ask().

这篇关于函数过早返回过滤器并降低了效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆