繁体   English   中英

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

[英]How to render a template after promise resolves?

我希望在解析promise之后返回要在父级中呈现的模板。 我知道价值不能从承诺中返回。 收到模板数据后,如何呈现模板?

在以下示例中,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
}

尝试aync-await操作....

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);
});

我写了一个例子。 ContentPane.prototype.getTemplate可以返回一个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);
  });

你可以像这样解决你的问题。 它适合我:

<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'))
  })

暂无
暂无

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

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