React Native如何从异步函数中获取变量并将其返回

时间:2019-07-18 15:34:01

标签: amazon-web-services react-native

我不知道如何从该函数中获取变量allP,因此我可以将其返回显示在屏幕上。

我尝试过在函数外部定义变量,这样我就可以在代码中调用它了,但是没有用。数组会在控制台日志中打印出来,但我似乎无法在返回中显示它。

sched = async () => {
var i = null;
var getPrice = null;
var allP =[];
try {
  const schedinfo = await API.graphql(graphqlOperation(netidget));
  this.setState({ schedinfo: schedinfo.data.listLoginModals.items });
  for (i = 0; i < schedinfo.data.listLoginModals.items.length; i++) { 
  getPrice = schedinfo.data.listLoginModals.items[i].Type;  
   var lowP = await API.graphql( 
    graphqlOperation(lowest, {
      CIndex: getPrice   
    })
    )  
    if(typeof lowP.data.listlowestprice.items[0] == "undefined") {     
      lowP = "-";    
    } else {
      lowP = lowP.data.listlowestprice.items[0].Price.toString(); 
    }  
    if(lowP == " ") { 
        lowP = "-"; 
      }          
  allP.push(lowP);     
  }
  console.log(allP);  
  {this.state.lowprices.map(da => ( 
          <View item={da} key={da.id}>
          <Text>{da.Price}</Text>
          console.log(da.Price) 
          </View>
                    ))}

  console.log(schedinfo.data.listLoginModals.items.length)
 } catch (err) {
  console.log('error creating restaurant...', err);
 }
};

我希望能够显示从该函数创建的allP数组。请任何帮助表示感谢,非常感谢

1 个答案:

答案 0 :(得分:0)

将您的代码try内移至新的异步功能,将其返回并在allP变量上接收该值(无箭头功能),因此:


constructor(){
   super();
   this.getAllP = this.getAllP.bind(this);
   this.sched = this.sched.bind(this);
}

async getAllP() {
   try {
   ....
   operations
   ....
   return allP
   }
}

async sched() {
   var allP = await getAllP();
}