为什么我需要在其他功能中再次异步/等待?

时间:2019-07-12 07:36:32

标签: javascript async-await

我很困惑为什么我需要在另一个函数中再次运行async / await

示例

async function fetchData() {
   try {
        const result = await axios.get('http://example.com')
        return result

    } catch(err) {
       return err

     }
}


// and in another function I need to async await again 

// if I want to get the value of fetchData() 

// or else it will return pending promise object


function mapData() {
     const data = fetchData()
     console.log(data) // is a Pending Promise    
}

如果我想获取数据而不是Promise对象

async function mapData() {
     const data = await fetchData() // I still need to await?? 
     console.log(data) // real value
}

我认为,如果我已经在fetchData函数中进行了异步/等待,那么它已经返回了一个值而不是诺言,为什么我需要再次进行异步/等待以在mapData函数中获得实际的数据?

2 个答案:

答案 0 :(得分:3)

async函数将始终返回Promise-一旦异步函数到达其末尾(在可能包含await的位置之后,它就会解决)。它不会神奇地使异步代码同步;异步函数的所有使用者也必须处理其异步性。

处理消费者中的错误通常也更有意义。在这里,对于fetchData中的错误,您似乎没有做任何特别的事情,因此您可以立即返回Promise,而不必在下游函数中await进行

function fetchData() {
   return axios.get('http://example.com');
}
async function mapData() {
     try {
       const data = await fetchData()
       console.log(data)
     } catch(e) {
       console.log('Something went wrong...');
       // handle failure of fetchData
     }
}

答案 1 :(得分:0)

承诺与时间有关。它们是最终将可用的值的包装器,但还没有。而且,直到该值可用为止,您才可以冻结整个应用程序。

异步/等待只是Promises上的语法糖。它使您可以编写

之类的代码
async function myFunction(){
  var id = await asyncMethod1();
  var value = await asyncMethod2(id);
  return syncMethod3(id, value);
}

代替

function myFunction(){
  return asyncMethod1().then(id => asyncMethod2(id).then(value => syncMethod3(id, value)));
}

但是它并没有改变它在下面的工作方式。

因此,尽管syncMethod3已同步,但返回值仍依赖于异步计算的值foobar。使myfunction异步。

每个调用myFunction的函数都需要等到myFunction计算出它的值,等等。

相关问题