2017-09-05 186 views
2

我是新来使用async/await - 我试图从API调用返回数据并格式化/稍微清理它。如何正确实现异步/等待

由于函数的异步性质,我真的很努力地研究如何使这项工作。如果没有浏览器的简单翻版,我无法承诺工作。

我的第一个函数调用API并获取响应为JSON。然后我保存这个数据json.recommendations

function getRecs() { 
    const requestUrl = `blahblah`; 
    const options = { 
     headers: { 
      'Content-type': 'application/json', 
      Accept: 'application/json', 
     }, 
     method: 'GET', 
    }; 

    fetch(requestUrl, options).then((res) => { 
     if (res.ok) { 
      return res.json(); 
     } 
     throw new Error('Error!!??', res); 
    }).then((json) => { 
     return json.recommendations; 
    }); 
} 

我的第二个函数接受json.recommendations和做一些整理,以删除不需要的数据并返回数据,那些符合我的过滤器的新阵列的一个子集。

async function getInStockRecs() { 
    const recs = await getRecs(); 
    if (recs !== undefined) { 
     return recs.filter(function(rec){ 
      return rec.isInStock === true; 
     }); 
    } 
} 

的第三个功能进一步格式化数据:

async function topThreeArray() { 
    const inStockRecs = await getInStockRecs(); 
    const topThree =[]; 
    for (let i = 0; i < i <= 3; i++) { 
     topThree.push(inStockRecs[0]); 
    } 
    return topThree; 
} 

通过使用await我打算每个功能仅一旦数据已经从以前的正常运行返回。然而,运行上述崩溃的页面,我不能做任何事情来调试,因为它只是崩溃。我哪里错了?

回答

2

你不要在你的getRecs()函数返回任何东西(你只返回在回调到fetch()调用)

由于您使用async-await其他地方,为什么不使用的getRecs()功能太?:

async function getRecs() { 
    const requestUrl = `blahblah`; 
    const options = { 
    headers: { 
     'Content-type': 'application/json', 
     Accept: 'application/json', 
    }, 
    method: 'GET', 
    }; 

    const res = await fetch(requestUrl, options); 
    if (res.ok) { 
     return res.json().recommendations; 
    } 
    throw new Error('Error!!??', res); 
} 

否则,你不得不返回fetch()调用本身:

return fetch(requestUrl, options).then((res) => { 
    ... 

浏览器崩溃的原因是因为topThreeArray()中的for循环中的条件很奇怪(i < i <= 3)并导致无限循环。
基本上,i < i的计算结果为false,它被隐式强制转换为0,所以条件有效地变为0 <= 3,这总是正确的。

最后,我想指出的是,您应该仔细考虑在浏览器中运行时首先是否适合async-await,因为对它的支持在浏览器中仍然非常脆弱和灵活。