如何在一个重复的函数上运行Promise?

问题描述 投票:0回答:1

我在Stencil组件里有一个重复的函数,直到建立一个菜单。

当我用Promise包住这个函数时,我在Stencil组件中得到一个错误。

renderMenu(obj, type, mobile) {

    let thisNested = this;

    return new Promise(function () {

      function checkMobile() {
        if (mobile) {
          return 'harmoni-navigation--' + type + '' + ' ' + 'harmoni-navigation--mobile';
        } else {
          return 'harmoni-navigation--' + type + '';
        }
      }

      return <div class={checkMobile()}>
        <ul>
          {
            Object.values(obj).map((object) => {
              return <li
                class={object['harmoniChildren']

                  /** Check if menu has any children. */

                  ? 'harmoni-navigation__item--' + type + '' + ' ' + 'harmoni-navigation__item--has-child'
                  : 'harmoni-navigation__item--' + type + ''}>

                <a href={object['url']}>
                  {object['title']}
                </a>

                {object['harmoniChildren'] && !mobile &&
                thisNested.renderMenu(object['harmoniChildren'], 'child', false)}

                {object['harmoniChildren'] && mobile &&
                thisNested.renderMenu(object['harmoniChildren'], 'child', true)}
              </li>
            })}
        </ul>
      </div>
    })
  }

这个错误是StencilJS特有的。vNode passed as children has unexpected type.Make sure it's using the correct h() function.empty objects can also be the cause, look for JSX comments that became objects.

然而,我认为问题出在我的代码中的某个地方,因为我以前从未使用过Promises。

希望有人能帮忙!

谢谢

javascript jsx es6-promise stenciljs
1个回答
0
投票

由于各种原因,renderer函数不能是异步的,所以你也不能在你的Stencil组件中等待async函数方法。render 方法。Stencil允许您在您的组件上设置各种生命周期方法(参见 组件生命周期文档),这些方法都可以是异步的。我们的想法是,你使用像 componentWillLoadcomponentDidLoad 来异步地准备你的组件的状态。

在你发布的代码中,你肯定没有正确地使用Promise API,因为你传递给 new Promise() 接收两个回调 resolvereject 其中你至少应该使用前者(否则你的承诺将永远无法实现)。有很多关于承诺的指南,你可以阅读(也许可以尝试一下。https:/www.promisejs.org 为开始)。)

在你的 renderMenu 函数需要异步行为,所以我不太确定你想用这个承诺来实现什么。既然你在评论中提到你想在组件渲染后对库进行初始化,我建议你尝试一下使用 componentDidLoad 方法,它是在你的组件渲染后执行的。

另外,你遇到的错误确实是由你的代码引起的,因为承诺不是Stencil知道如何渲染的东西。

© www.soinside.com 2019 - 2024. All rights reserved.