如何在承诺解决后呈现模板?

How to render a template after promise resolves?

我想 return 一个模板在解析 promise 后在父级中呈现。我知道不能从承诺中 return 获取价值。收到模板数据后如何渲染模板?

在下面的示例中,ContentPane 是列出所有要呈现的模板的父级。 Films中调用网络,需要渲染模板。

ContentPane.prototype.getTemplate = function(){
    let template = `
        <div class="contentPane" id="contentPane">
        ${new Films().render()}
        </div>
    `;
    return template;
}


Films.prototype.render =  function(){
    var template =  this.getTemplate();
    template.then(function(val){
        return val;
    })
    //based on the value resolved by promise,
//appropriate template should be returned to parent
}

Films.prototype.getTemplate = async function(){
  //make network call
  //create template based on server response
}

我写个例子。 ContentPane.prototype.getTemplate 可以 return 一个 promise,然后你可以从 then 回调函数中获取模板。像这样 new ContentPane().getTemplate().then(template => { console.log(template); });

  const ContentPane = function() {}
  const Films = function () {}

  ContentPane.prototype.getTemplate = async function(){
    const filmsTemplate = await new Films().render();
    let template = `
        <div class="contentPane" id="contentPane">
        ${filmsTemplate}
        </div>
    `;
    return template;
  }


  Films.prototype.render =  function(){
    var template =  this.getTemplate();
    return template.then(function(val){
      return val;
    })
    //based on the value resolved by promise,
    //appropriate template should be returned to parent
  }

  Films.prototype.getTemplate = async function(){
    //make network call
    //create template based on server response
    return await new Promise((resolve) => {
      resolve('123')
    })
  }

  new ContentPane().getTemplate().then(template => {
    console.log(template);
  });

尝试异步等待操作....

const ContentPane = function() {}
const Films = function () {}

ContentPane.prototype.getTemplate = async function(){
  let template = `
      <div class="contentPane" id="contentPane">
      ${await new Films().render()}
      </div>
  `;
  return template;
}
Films.prototype.render =  async function(){
  var value =  await this.getTemplate();
  return value;
}
Films.prototype.getTemplate = async function(){
   return new Promise((res, rej) => {
       setTimeout(() => {
           res('123');
        }, 1000);
    });
}
new ContentPane().getTemplate().then(template => {
  console.log(template);
});

你可以这样解决你的问题。 它对我有用:

<items ref="items" :all="all" @remove="removeItem" />

和==>

this.$api.productCategories.delete(item.id , true)
  .then(res => { 
    this.all = this.all.filter(i => i.id !== item.id) this.$showSuccess(this.$t('productCategories.productCategoryRemoved'))
    this.$nextTick(() => {
      this.$refs.items.reinit()
    })
  })
  .catch(err => {
    this.$showError(this.$getLocaleErrorMessage(err, 'productCategories'))
  })