简体   繁体   English

如何等待使用 async-await 创建元素?

[英]How to wait for elements to be created with async-await?

hope you all are having a good day.希望你们今天过得愉快。

I try to make fillClassData() wait for createClassElementsWith() .我尝试让fillClassData()等待createClassElementsWith() I figured I have to use async await and return a promise, data somehow to make it work.我想我必须使用异步等待并返回 promise,数据以某种方式使其工作。 Any ideas how to solve this in a clean readable way?任何想法如何以一种清晰易读的方式解决这个问题? What would I return?我会返回什么?

Code:代码:

// get data
async function fillClassData() {
  const prop_id = prop_select.children('option:selected').val();
  const selected_class = config.getClass();
  // fetch data
  const data = await api.fetchClass(prop_id);

  // create options
  await createClassElementsWith(data);

  if (itemsExist(selected_class)) {
    class_select.val(selected_class);
    // fill table info
    fillTableData();
  }
}

// creates options for classes
async function createClassElementsWith(data) {
  // clear options
  class_select.find('option').remove();
  // create new options per entry
  if (data.length <= 0) {
    generateOption('default', 'No options yet', class_select);
  } else {
    generateOption('default', 'Select Class...', class_select);
    for (let item of data) {
      generateOption(item.class_id, item.class_name, class_select);
    }
  }
  class_select.children('option')[0].selected = true;
}

// creates element with given parameters
function generateOption(value, text, select) {
  // create element
  let opt = document.createElement('option');
  opt.value = value;
  opt.innerHTML = text;
  // set some options to disabled
  if(value === 'default') opt.setAttribute('disabled', true);
  // append to select
  select.append(opt);
}

data example:数据示例:

class_id: "3179807"
class_longname: "long class name"
class_name: "short class name"

Btw.顺便提一句。 the function fillClassData() is called based on a select option of a prop .基于prop的 select 选项调用 function fillClassData() The function fillTableData() fills in a table with the data gotten based on those two selects. function fillTableData()使用基于这两个选择获得的数据填充表格。

My favorite workaround for something like this is to add a setTimeout() .我最喜欢的解决方法是添加一个setTimeout() The delay can be 1 ms or 5ms, whichever seems more dependable to you.延迟可以是 1 毫秒或 5 毫秒,以您认为更可靠的为准。 Put all of the code that depends on createClassElementsWith in the timeout.将所有依赖于createClassElementsWith的代码放入超时中。

// get data
async function fillClassData() {
  const prop_id = prop_select.children('option:selected').val();
  const selected_class = config.getClass();
  // fetch data
  const data = await api.fetchClass(prop_id);

  // create options
  createClassElementsWith(data); // Nothing to wait for like evolutionxbox said

  setTimeout(() => {
    if (itemsExist(selected_class)) {
      class_select.val(selected_class);
      // fill table info
      fillTableData();
    }
  }, 1); // 1 ms should be enough time for createClassElements to run
}

// creates options for classes
function createClassElementsWith(data) {
  // clear options
  class_select.find('option').remove();
  // create new options per entry
  if (data.length <= 0) {
    generateOption('default', 'No options yet', class_select);
  } else {
    generateOption('default', 'Select Class...', class_select);
    for (let item of data) {
      generateOption(item.class_id, item.class_name, class_select);
    }
  }
  class_select.children('option')[0].selected = true;
}

// creates element with given parameters
function generateOption(value, text, select) {
  // create element
  let opt = document.createElement('option');
  opt.value = value;
  opt.innerHTML = text;
  // set some options to disabled
  if(value === 'default') opt.setAttribute('disabled', true);
  // append to select
  select.append(opt);
}

I figured it out.我想到了。 Big thanks to the people commenting and trying to help but the problem was somewhere completely else.非常感谢评论并试图提供帮助的人,但问题完全出在其他地方。 I guess my debugging skills are not the greatest and I started looking at the wrong end.我想我的调试技能不是最好的,我开始看错了。

I saved selected options in the local storage but I didn't clear the saved class whenever a new prop was selected.我将选定的选项保存在本地存储中,但我没有清楚选择新的Prop时,我没有清楚保存的prop Which means the data can't be fetched correctly, the parameters don't match up.这意味着无法正确获取数据,参数不匹配。 I added a function to my config now: config.clearClass();我现在在我的配置中添加了一个 function: config.clearClass(); which clears the class item in the localstorage.这将清除本地存储中的 class 项。

The word async has one simple meaning: this function always returns a promise.异步这个词有一个简单的含义:这个 function 总是返回一个 promise。 Other types of values are automatically wrapped in a successful promise.其他类型的值会自动包装在成功的 promise 中。

async function f() { return 1; }

You can explicitly return a promise, the result will be the same:你可以显式返回一个 promise,结果是一样的:

async function f() {

return Promise.resolve(1);返回 Promise.resolve(1); } }

f().then(alert); // 1

The await keyword will cause the JavaScript interpreter to wait until the promise to the right of await is executed. await 关键字将导致 JavaScript 解释器等待直到执行 await 右侧的 promise。 After which it will return its result, and the code execution will continue.之后它将返回结果,代码执行将继续。 // Works only inside async functions // 仅适用于异步函数

let value = await promise;

enter code here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM