React Native 中意想不到的承诺

Unexpected Promise in React Native

我不熟悉 React Native 和一般编码。我为 upwork 支付了一些代码,但很难将其集成到我的程序中。

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)
}

我相信当 运行ning pullTimeLine() 程序返回一个包含三个承诺的数组时。 (我在 pullBatch() 之前也有 运行 带有 "await" 的代码,但它错误地告诉我 await 是一个保留字)这意味着我犯了两个错误:

  1. 我没有正确理解 JS 中的承诺或它们是如何解决的。
  2. 我错误地连接了数组。

我一直在努力学习,因此,虽然我非常感谢有关代码修复的建议,但如果您能教我了解我的理解失误所在,我也将不胜感激。

谢谢

让我们分解一下。您似乎明白 pullBatch 是一个异步函数,因此调用它将 return 由 twitterRest 交互创建的承诺。

问题是您在 for 循环中对 pullBatch 的调用不会解决这些承诺(这似乎是您想要做的)。最简单的方法是对 currentBatch 使用 await,但是当您尝试时,您遇到了保留错误。基本上你只需要像这样使 pullTimeline 异步:

async pullTimeline(){
  ...

只要意识到一旦你这样做了,pullTimeline 现在是一个异步函数,它也将是 return 一个 promise。所以要使用此功能,您需要使用 .then(),例如:

pullTimeline().then(timeLine => {
  // do something with your timeline here
})

或者,如果您在另一个异步函数中使用它,则可以使用 await。

const timeLine = await pullTimeline() // must be inside async function

基本上在您的调用链中的某个点,您将不得不使用 .then() 解决一个承诺,或者通过创建一个顶级异步函数来忽略顶级承诺。例如:

async useTimeline() {
  const timeLine = await pullTimeline()
  // do something with your timeline
}

// call the function above, and just disregard its promise
useTimeLine()

只是不要忘记在某处处理错误。在您的顶级承诺中使用 .catch(),或在您的任何等待调用周围使用 try / catch