【问题标题】:Trying to return an ID using Wix Velo and Promises尝试使用 Wix Velo 和 Promises 返回 ID
【发布时间】:2021-09-10 17:57:11
【问题描述】:

我正在尝试使用已登录用户的 Wix Velo 检索 _id 字段。代码正在运行,但是我正在使用的函数返回 [object Promise] 而不是我需要的 id 字符串。

import wixData from 'wix-data';

export function getID() {
    return wixData.query("Picks") // My Collection
        .eq("player", "Gary") // A field, and a cell
        .find()
        .then((results) => {
            if (results.items.length > 0) {
                let firstItem = results.items[0]._id; 
                console.log("Return ID: " + firstItem) // This returns the ID I need
                $w("#text31").text = firstItem;
            //    return firstItem.toString();
            } else {
                console.log("No Items Found")
            }
        })
        .catch((err) => {
            let errorMsg = err;
        });
}
 
console.log("Return the ID outside of the function: " + getID()) // This returns "[object Promise]"

我尝试使用 await,但它只会给我错误。

【问题讨论】:

    标签: javascript velo


    【解决方案1】:

    由于所有浏览器都在顶级等待is not supported,我相信Wix 也没有打开该功能。相反,用异步 IIFE 包装它。

    (async () => {
      console.log("Return the ID outside of the function: " + await getID())
    })();
    

    这个answer有更多关于top-level-await的细节

    【讨论】:

      【解决方案2】:

      以防万一这对其他人有所帮助,答案就在嵌套的承诺中。我必须调用第一个函数 getLoggedInUserName() 来获取用户名,然后将其传递给一个名为 getID() 的嵌套函数。

      本质上,这是一个范围问题,并且还在等待解决承诺。

      getLoggedInUserName().then((results) => {
          let userName = results;
      
          getID(userName).then((results) => {
              let userID = results;
              let pick = $w("#dropdown1").value;
      
              let toUpdate = {
                  "_id": userID,
                  "pick": pick,
                  "player": userName,
                 
              }
              wixData.update("Picks", toUpdate)
                  .then((results) => {
                      $w("#text33").show();
                      let item = results;
                  })
                  .catch((err) => {
                      let errorMsg = err;
                      console.log("Error: " + errorMsg)
                  });
          })
      })
      .catch((err) => {
          let errorMsg = err;
      });
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-10
        • 2017-10-19
        • 1970-01-01
        • 2012-07-09
        • 2015-07-11
        • 2016-01-13
        • 2019-01-23
        • 1970-01-01
        相关资源
        最近更新 更多