异步方法返回未定义

时间:2019-09-29 13:00:09

标签: javascript async-await

我正在尝试进行异步调用以返回结果。结果是成功的,但是无论我如何尝试-调用者始终看到未定义。你能帮我看看我做错了吗。

Çaller:(总是变得不确定)

<html>
<head></head>
<body>
<section>
<input type="button" value="Function with Parameters and Return Value"     onClick="testParamsReturn()">
</section>
<script>
function getInput(request){
var message = "Enter details here";
return message;
}
function testParamsReturn(){
var firstName = "Name1";
function getInput("first_name") return firstName;
var secondName = "Name2";
function getInput("second_name") return secondName;
alert ("Testing a function with parameters and a return value of" + firstName + secondName);
} 

目标:(从我的日志中将returnShares推送并填充)

 groups.forEach(async group =>{
        let foundShares =  await group.getShares();
        console.log("found shares ", foundShares)

1 个答案:

答案 0 :(得分:1)

看一下这篇文章,看看为什么在forEach中等待是行不通的。 https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404

将forEach替换为:

for (const group of groups) {
    let foundShares =  await group.getShares();
    console.log("found shares ", foundShares)
}