当我期望一个数组时,取回承诺

时间:2019-05-16 15:35:28

标签: javascript reactjs

我正在做一个简单的api get请求,但是我似乎无法单独隔离数组。它总是在promise之内,我不确定如何删除它或如何访问存储在数组中的值。

'use strict';

//  Required module
const ruleSet = require('validate-table-rules');

// Attach module to Object prototype
Object.prototype.rule = ruleSet.rules;

// Declare and object
const object = [
    {Age: 18, Required: 21}
];

// Sample case -> pass in names you
// want to check for in attached object
console.log(object.rule('[Age] < [Required]')) // output = true
console.log(object.rule('[Age] > [Required]')) // output = false
function getLocation(name) {

  let output = fetch(`http://dataservice.accuweather.com/locations/v1/cities/search?apikey=oqAor7Al7Fkcj7AudulUkk5WGoySmEu7&q=london`).then(data => data.json());
  return output

}

function App() {

  var output = getLocation(`london`);
  console.log (output)
...

是console.log中显示的内容。我只需要Array(3)

1 个答案:

答案 0 :(得分:3)

fetchPromise#then总是返回承诺。要访问其获取的信息,请使用承诺:

getLocation()
.then(data => {
    // use the data
})
.catch(error => {
    // Handle/report the error
});

或在异步函数中:

const data = await getLocation();

旁注:您的getLocation有一个非常常见错误(在我贫乏的小博客上,这是常见的我wrote it up):它不会检查HTTP操作是否成功。 fetch仅在 network 错误而不是HTTP错误时失败。要解决它:

function getLocation(name) {
    return fetch(`http://dataservice.accuweather.com/locations/v1/cities/search?apikey=oqAor7Al7Fkcj7AudulUkk5WGoySmEu7&q=london`)
    .then(response => {
        if (!response.ok) {
            throw new Error("HTTP error, status = " + response.status);
        }
        return response.json();
    });
}