从数组返回值时获取未定义 - Node JS

JiLan

我是 NodeJS 的新手,我在它的异步特性方面遇到了一些困难。

我正在使用异步函数请求一些数据。我的第二个函数用于在知道名称的同时检索 ID(两个信息都存储在第一个函数返回的数据中)。

每次我在控制台中得到“找到它”,但在循环结束之前执行返回并且我得到一个“未定义”。

我应该使用回调还是使用 async & await ?即使在对 async & await 和回调进行了大量研究之后,我也无法找到让它工作的方法!

async function getCustomers() {
        try {
             var customers = await axios({
                //Query parameters
            });
            return customers;
        }
        catch (error) {
            console.log(error);
        }
    }


function getCustomerId(customerName){
        var customerId = null;
        getCustomers().then(function(response){
            for (const  i of response.data){
                console.log(i['name']);

                if(i['name'] == customerName){
                    console.log('Found it !'); //This got displayed in the console
                    customerId = i['id'];
                    return customerId; //This never return the desired value
                    }
                }
            });

    }

console.log(getCustomerId('abcd'));

感谢您提供的任何帮助!

马丁·雷诺

您正在打印 getCustomerId 的输出,但它不返回任何内容。

尝试使用以下命令返回 Promise:

return getCustomers().then(function(response) {...});

然后,而不是:

console.log(getCustomerId('abcd'));

你应该试试:

getCustomerId('abcd').then(function(id) {console.log(id);})

以便在尝试显示其输出之前确定 Promise 已解决

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章