【问题标题】:chaining promise where 2nd promise is dependent on the result of the first链接承诺,其中第二个承诺取决于第一个承诺的结果
【发布时间】:2021-02-18 23:41:31
【问题描述】:

在我的 react native 应用程序中将两个 Promise 链接在一起时遇到了很多麻烦。第一个承诺成功地在异步存储中获取一个值并将其设置为状态。第二个 promise 获取我从 Firebase 获得的数据,但取决于我从第一个 promise 中设置的状态。任何帮助将不胜感激。

import React, { useState, useEffect } from "react";
import { Text, StyleSheet, View } from "react-native";
import firebase from "../../firebase/fbConfig";
import AsyncStorage from "@react-native-async-storage/async-storage";

let DB = firebase.firestore();

function Questions(props) {
    const [productId, setProductId] = useState("");
    const [question, setQuestion] = useState("");
    const [reward, setReward] = useState("");

    const getAsyncData = () => {
        AsyncStorage.getItem("key").then((value) => setProductId(value))
        // works fine //
    };

    const getDataFromFirebase = (productId) => {
        DB.collection("ads")
            .where("productId", "==", productId)
            .get()
            .then(function (querySnapshot) {
                querySnapshot.forEach(function (doc) {
                    setQuestion(doc.data().question);
                    setReward(doc.data().reward);
                });
            })
            .catch(function (error) {
                console.log("Error getting documents: ", error);
            });
            // works fine //
    };

    useEffect(() => {
        getAsyncData().then((productId) => getDataFromFirebase(productId));
        // does not work //
    });

    return (
        <>
            <View style={styles.container}>

            </View>
        </>
    );
}

export default Questions;

【问题讨论】:

  • 你的问题是getAsyncData 没有返回任何东西...试试const getAsyncData = () =&gt; { return AsyncStorage.getItem("key").then((value) =&gt; setProductId(value)); };const getAsyncData = () =&gt; AsyncStorage.getItem("key").then((value) =&gt; setProductId(value));

标签: javascript reactjs firebase react-native promise


【解决方案1】:

试试这个方法

useEffect(() => {
  getAsyncData();
}, []);

const getAsyncData = async () => {
  try {
    const productId = await AsyncStorage.getItem("key");
    getDataFromFirebase(productId);
  } catch (error) {
    console.log(error);
  }
};

【讨论】:

  • 这对我有用!我也有一个类型错误,但终于让它工作了
猜你喜欢
  • 1970-01-01
  • 2015-09-26
  • 2019-12-21
  • 2017-12-21
  • 1970-01-01
  • 2021-05-19
  • 1970-01-01
  • 2013-11-25
  • 1970-01-01
相关资源
最近更新 更多