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

时间:2019-04-29 02:57:25

标签: javascript ecmascript-6 es6-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
}

3 个答案:

答案 0 :(得分:1)

尝试执行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);
});

答案 1 :(得分:0)

我写一个例子。 getDisplayValues() { let displayedDefects = []; this.state.rows.map((qc) => qc.BinsByDayByOrchardsQCs.map((qc2) => qc2.BinsByDayByOrchardsQCsDefects.map((qc3) => if(defectsArray.includes(qc3.Defect)){ displayedDefects.push(qc3.Defect); } ) ) ); displayedDefects.sort(); return displayedDefects.map((defect)=>( <div className = "row label" > <div className = "column-label bold" > {defect} </div> </div> ); } render(){ return {this.getDisplayValues()} } 可以返回一个Promise,然后您可以从ContentPane.prototype.getTemplate回调函数中获取模板。像这样then

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

答案 2 :(得分:0)

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

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