从Promise设置对象数组

时间:2018-02-28 19:20:00

标签: javascript arrays reactjs



function getSuggestions(inputValue) {
  let results = [];
  axios.get(`${API_URL}?queryString=${inputValue}`)
    .then(({ data }) => {
      results = data;
    })
  let textValues = results.map(r => (textValues.push(r.text.toUpperCase())));
  //push all unique values to Set
  let uniqSet = new Set(textValues);
  //turn Set into Array object
  let uniqArr = Array.from(uniqSet)
  let suggestions = uniqArr.map(r => (suggestions.push({'label': r.text.toUpperCase()})));
  return suggestions.filter(suggestion => {
    const keep =
      (!inputValue || suggestion.label.toLowerCase().includes(inputValue.toLowerCase())) &&
      count < 5;

    if (keep) {
      count += 1;
    }

    return keep;
  });
}
&#13;
&#13;
&#13;

我有这个功能来创建一个自动完成的搜索组件,我在其中输入用户输入的inputValue并将其发送到端点,然后端点返回搜索项的对象。

我正在尝试将此空results数组设置为使用axios从我的提取返回的data对象。无论我尝试什么,结果数组总是保持空白。有什么建议?先感谢您。

1 个答案:

答案 0 :(得分:1)

axios代码是异步的,其余代码不是(并且不等待异步代码)。如果您不需要支持旧浏览器,最好的办法是使用async/await

async function getSuggestions(inputValue) {
  let results = await axios.get(`${API_URL}?queryString=${inputValue}`).then(({ data }) => data)
  let textValues = results.map(r => (textValues.push(r.text.toUpperCase())));
  //push all unique values to Set
  let uniqSet = new Set(textValues);
  //turn Set into Array object
  let uniqArr = Array.from(uniqSet)
  let suggestions = uniqArr.map(r => (suggestions.push({'label': r.text.toUpperCase()})));
  return suggestions.filter(suggestion => {
    const keep =
      (!inputValue || suggestion.label.toLowerCase().includes(inputValue.toLowerCase())) &&
      count < 5;

    if (keep) {
      count += 1;
    }

    return keep;
  });
}

否则你的函数可能需要返回一个promise,因为结果是异步的:

function getSuggestions(inputValue) {
  return axios.get(`${API_URL}?queryString=${inputValue}`).then(({ data }) => {
    let textValues = data.map(r => (textValues.push(r.text.toUpperCase())));
    //push all unique values to Set
    let uniqSet = new Set(textValues);
    //turn Set into Array object
    let uniqArr = Array.from(uniqSet)
    let suggestions = uniqArr.map(r => (suggestions.push({'label': r.text.toUpperCase()})));
    return suggestions.filter(suggestion => {
      const keep =
        (!inputValue || suggestion.label.toLowerCase().includes(inputValue.toLowerCase())) &&
        count < 5;

      if (keep) {
        count += 1;
      }

      return keep;
    });
  })  
}

getSuggestions('test').then(keep => {
  // do something with response
})