React Native中意外的承诺

问题描述 投票:1回答:1

我是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是一个保留字)这意味着我犯了两个错误:

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

我一直在努力学习,所以虽然我非常感谢代码修复的建议,但如果你教我理解错误在哪里,我也非常感激。

谢谢

javascript reactjs api es6-promise fetch-api
1个回答
2
投票

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

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

async pullTimeline(){
  ...

只要意识到,一旦你这样做,pullTimeline现在是一个异步函数,也将返回一个承诺。因此要使用此功能,您需要使用.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

© www.soinside.com 2019 - 2024. All rights reserved.