简体   繁体   English

调用 async / await function 并接收返回值

[英]Calling async / await function and receiving a value back

I have got a function in an API library that calls firestore and gets data back.我在调用firestore并取回数据的API库中有一个function。 This part works fine:这部分工作正常:

export const getUserByReferrerId = async id => {
  let doc = await firestore
    .collection(FIRESTORE_COLLECTIONS.USERS)
    .where('grsfId', '==', id)  
    .get()  
    .then(querySnapshot => {
      if (!querySnapshot.empty) {
        console.log ("we found a doc");
        // use only the first document, but there could be more
        const snapshot = querySnapshot.docs[0];
        console.log ("snapshot", snapshot.id);
        return snapshot.id  // uid of the user
      }
    });
}

I am calling this library from a component.我从一个组件调用这个库。 I have another function that runs on a button click.我有另一个 function 可以在单击按钮时运行。 I cannot figure out how to get the value from the async api call.我无法弄清楚如何async api 调用中获取值。

I have tried this - a promise appears when I console.log the return:我试过这个 - 当我console.log登录返回时出现 promise:

testCreditFunction = (id) => {
    let uid = getUserByReferrerId(id).then(doc => { 
        console.log("uid1", doc);    
    });
}

I have also tried this - log shows null for uid .我也试过这个 - 日志显示 null 为uid

testCreditFunction = (id) => {
    let uid = '';
    
    (async () => {
        uid = await getUserByReferrerId(id);
        console.log ("uid in the function", uid);
    })();
}

I have seen this question asked a few times and I have tried several of the answers and none are working for me.我已经看到这个问题被问了几次,我已经尝试了几个答案,但没有一个对我有用。 The odd thing is that I have done this same thing in other areas and I cannot figure out what the difference is.奇怪的是,我在其他领域也做过同样的事情,我不知道有什么区别。

One thing I notice right off the bat is that you're mixing async/await & .then/.error .我立即注意到的一件事是您正在混合async/await.then/.error While it's not strictly forbidden it definitely makes things more difficult to follow.虽然它不是严格禁止的,但它肯定会让事情变得更加难以遵循。

As others have mentioned in the comments, you need to make a return for the promise to resolve (complete).正如其他人在评论中提到的,您需要返回 promise 才能解决(完成)。 Here's how you might write getUserByReferrerId (using async/await).以下是您可以如何编写getUserByReferrerId (使用 async/await)。

const getUserByReferrerId = async id => {
  const usersRef = firestore.collection('users');
  const query = usersRef.where('grsfId', '==', id);

  const snapshot = await query.get();
  if (snapshot.empty) {
   console.log('no doc found');
   return;
  }

  console.log('doc found');
  const doc = snapshot.docs[0]; // use first result only (there might be more though)
  return doc.id
}

You'll notice how I split up the query building steps from the snapshot request.您会注意到我如何将查询构建步骤与快照请求分开。 This was intentional as the only promised function in this is the get request.这是故意的,因为这是get请求中唯一承诺的 function。

Using this getUserByReferrerID can be done with a simple await .使用这个getUserByReferrerID可以通过一个简单的await来完成。 Just be sure to check that the result isn't undefined.请务必检查结果是否未定义。

const userID = await getUserByReferrerId('someid')

if (!userID) {
  console.log('user not found');
}

console.log(`User ID is ${userID}`);
  

ps - I would recommend renaming the function to getUserIdByReferrerId to more accurately reflect the fact that you're returning an ID and not a user doc. ps - 我建议将 function 重命名为getUserIdByReferrerId以更准确地反映您返回的是 ID 而不是用户文档的事实。 Alternatively, you can return the user object and leave the name as is.或者,您可以返回用户 object 并保持名称不变。

Change your funtion to this.将您的功能更改为此。

export const getUserByReferrerId = async id => {
  return await firestore
  .collection(FIRESTORE_COLLECTIONS.USERS)
  .where('grsfId', '==', id)  
  .get();
}

Try getting data this way.尝试以这种方式获取数据。

 testCreditFunction = (id) => {

 let querySnapshot = '';
        
    (async () => {
      querySnapshot = await getUserByReferrerId(id);
      const snapshot = querySnapshot.docs[0];
      console.log ("snapshot", snapshot.id);
  })();

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

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