【问题标题】:Unexpected Promise in React NativeReact Native 中的意外 Promise
【发布时间】:2019-07-18 10:42:02
【问题描述】:

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

我相信在运行 pullTimeLine() 时,程序会返回一个包含三个 Promise 的数组。 (我也在 pullBatch() 之前用“await”运行了代码,但是告诉我 await 是一个保留字会出错)这意味着我犯了两个错误:

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

我一直在努力学习,所以虽然我非常感谢有关代码修复的建议,但如果您能告诉我我在理解方面的失误在哪里,我也非常感激。

谢谢

【问题讨论】:

    标签: javascript reactjs api es6-promise fetch-api


    【解决方案1】:

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

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

    async pullTimeline(){
      ...
    

    只要意识到,一旦你这样做了,pullTimeline 现在是一个异步函数,它也会返回一个 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

    【讨论】:

    • 这样一个深思熟虑和有益的回应。非常感谢。接受了你的建议,经过一些修补(比我自豪地承认的更多的猜测和检查),我让事情运行起来了。再次感谢
    猜你喜欢
    • 2018-12-08
    • 1970-01-01
    • 2020-01-18
    • 2015-06-01
    • 2016-07-16
    • 2016-11-04
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多