问题描述
我是React Native和编码的新手。 我花了一些代码来完成工作,并且很难将其集成到我的程序中。
async pullBatch(since){
    let param = {
        userScreenName: '?screen_name=google',
        count: "&count=5",
        retweets: "&include_rts=false",
        replies: "&exclude_replies=false",
        trim: "&trim_user=true",
        since: "&max_id=" + since
    };
    let twitterRest = new TwitterRest(); //create a new instance of TwitterRest Class   
    let batch = await twitterRest.pullTweets(param); //pull the Google TimeLine
    return batch;
}
pullTimeline(){
    let timeLine = []
    for(i = 0; i <= 2; i++){
        let currentBatch = this.pullBatch("1098740934588751900")
        console.log(currentBatch);
        timeLine = timeLine.concat(currentBatch);
    }
    console.log(timeLine);
    // timeLine = currentBatch
    return(timeLine)
}
我相信,当运行pullTimeLine()时,程序将返回三个promise的数组。 (在pullBatch()之前,我也使用“ await”运行了代码,但是错误地告诉我await是保留字)这意味着我犯了两个错误:
- 我没有正确理解JS中的承诺或如何解决它们。
- 我错误地串联了数组。
我一直在努力学习,因此,尽管我非常感谢有关代码修复的建议,但如果您能教给我有关理解的错误之处,我也将不胜感激。
谢谢
1楼 
  
    Matt Way 
    2 
   已采纳 
    2019-02-25 03:53:54
  
 
  
     让我们分解一下。 
     您似乎了解了pullBatch是一个异步函数,因此调用它会返回由twitterRest交互创建的Promise。 
 
     问题是您在for循环中对pullBatch的调用将无法解决这些承诺(这似乎是您想要做的)。 
     最简单的方法是对currentBatch使用await ,但是在尝试时得到了保留的错误。 
     基本上,您只需要使pullTimeline异步,如下所示: 
async pullTimeline(){
  ...
 
     只要意识到,一旦执行此操作, pullTimeline现在就是一个异步函数,该函数还将返回一个pullTimeline 。 
     因此,要使用此功能,您需要使用.then() ,例如: 
pullTimeline().then(timeLine => {
  // do something with your timeline here
})
或者,如果您在另一个异步函数中使用它,则可以使用await。
const timeLine = await pullTimeline() // must be inside async function
 
     基本上,在调用链中的某个时刻,您将必须使用.then()来解决promise,或者通过创建顶级异步函数来忽略顶级promise。 
     例如: 
async useTimeline() {
  const timeLine = await pullTimeline()
  // do something with your timeline
}
// call the function above, and just disregard its promise
useTimeLine()
 
     只是不要忘记在某个地方处理错误。 
     在顶级.catch()上使用.catch() ,或在任何等待调用中使用try / catch 。