异步/等待似乎不起作用

时间:2018-06-21 01:57:49

标签: javascript asynchronous async-await

我不确定这是怎么回事。但是我有一个函数可以使用axios进行简单的API调用,它所做的只是返回来自API调用的字符串。

Map<Integer,String> hm1 = new HashMap<Integer,String>();
String line;
// while there is a line to be read
while ((line = reader.readLine()) != null) {
    // we need to tokenize the line. the common separator is ", "
    // so that it what we shall split it by, to get an array of each value between ", "
    String[] tokens = line.split(",\\s"); //(in regex, \\s matches a whitespace such as a space)
    // if the space is unreliable, it can be made optional: line.split(",\\s?")
    // loop for each record
    for (int i = 0; i != tokens.length; i++) {
        // next we need to get the "data" portion of the record, which is after the '='
        /*
        ** we could use regex again
        ** i.e. tokens[i].split("=")[1] will be the "data"
        ** but as a general rule, if you can do it easily without regex, don't use regex.
        ** it might look innocent enough, but a lot goes on in a regex engine!
        **
        ** instead we just get the index of '=' in the string
        ** add 1 to move past it
        ** and then get the characters from that index onward
        ** i.e. tokens[i].substring(tokens[i].indexOf('=')+1)
        */
        //get the index at which the data starts in the string
        int dataIndex = tokens[i].indexOf('=') + 1;
        //get the chars from that index onward
        String data = tokens[i].substring(dataIndex);
        //insert it into the map
        hm1.put(new Integer(i),data);
    }
}

这按预期进行,问题是当我在另一个函数中调用async function callSomeApi () { const res = await axios.get('http://someapi.com') console.log(res) // here I get the value I expected return res // this is going to be a simple string } 时。事情在

之前运行
callSomeApi

很明显,我对async / await有一些误解,但我不太了解。如何修复我的代码?

1 个答案:

答案 0 :(得分:0)

我发现了这一点,事实证明它与async/await无关。好吧,它确实做到了,但是不像我想象的那样。我将其留在此处,以防其他人遇到相同的情况并相应地更新OP。

在我的someApiCall的示例代码中,为简单起见,我返回了一个字符串。但实际上,我正在返回一个包含所需字符串的对象。所以想像res像这样:

{
  myString: 'blah'
  somethingElse: 'blabla'
}

这很可爱,但是当需要在doSomething调用中使用它时,我实际上是在这样做:

async function doSomething () {
  const someApiRes = await callSomeApi().myString // here is how it was actually being done
  console.log('I will be displayed before someApiRes is finished.')
  console.log(`someApiRes will be undefined: ${someApiRes}`)
}

我愚蠢地没有意识到await不会运行我的函数,然后访问了myString属性,我什至没有想到在编写我的代码时可能会遇到问题问题。

因此,解决我的问题的方法如下:

async function doSomething () {
  const someApiRes = await callSomeApi()
  const myString = someApiRes.myString()
  console.log('This is all working as expected.'))
}