【问题标题】:js: promises inside a while- true loop [duplicate]js:在 while-true 循环中承诺 [重复]
【发布时间】:2018-06-11 20:40:29
【问题描述】:

我在从 youtube 播放列表中检索所有数据时遇到了一些困难。这是我的代码:

function getApiUrl(nextPageToken) {
    return '<api_url>' + '&playlistId=' + '<playlistId>' + (nextPageToken !== null ? '&pageToken=' + nextPageToken : '');
}

function getPlaylist() {
    var titles = [],
        nextPageToken = null,
        url = getApiUrl(null);

    while(true) {
        // returns new Promise(...)
        doRequest(url).then(data => {
            // process data : push items to titles array
            nextPageToken = data.nextPageToken;
        });

        if (nextPageToken === undefined) {
            break;
        }

        url = getApiUrl(nextPageToken);
    }

    // returns empty array
    return titles;
}

试图打破数据处理程序内部的循环导致SyntaxError: Illegal break statement

【问题讨论】:

  • 使用与生成器函数无关的无限循环通常不是一个好主意。你应该在这里做的是将一个变量设置为true,当nextPageToken === undefined时,将变量设置为false。这将停止循环
  • @SterlingArcher 仍然没有解决空数组的问题
  • @SterlingArcher 不会因为对 nextPageToken 的分配是异步的而不起作用吗?
  • 您必须将所有代码汇总到then 才能正常工作。忙于等待承诺可能弊大于利。

标签: javascript asynchronous promise youtube-api


【解决方案1】:

您遇到的问题是循环是同步的,但 nextPageToken 的分配是异步的。我实际上不确定,但是使用递归可以实现类似的工作

function getList(url){
    return doRequest(url).then(data => {
        if(data.nextPageToken !== undefined){
            //titles.push()... whatever you're putting into titles
            var nextUrl = getApiUrl(data.nextPageToken);
            return getList(nextUrl);
        }else{
            return;
        }
    });
}

【讨论】:

    【解决方案2】:

    我认为你可以使用await 运算符。

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

    function getApiUrl(nextPageToken) {
        return '<api_url>' + '&playlistId=' + '<playlistId>' + (nextPageToken ? '&pageToken=' + nextPageToken : '');
    }
    
    async function getPlaylist() {
        var titles = [],
        nextPageToken = null,
        url = getApiUrl(null);
    
    
        // returns new Promise(...)
        nextPageToken = await doRequest(url).nextPageToken;
    
        url = getApiUrl(nextPageToken);
    
        // returns empty array
        return titles;
    }
    

    【讨论】:

    • getPlaylist 必须标记为异步
    • 哦,也许我很困惑。我认为 OP 需要走多页。我试图想办法将 async/await 集成到 while 循环中,但没有。
    猜你喜欢
    • 2015-11-13
    • 2017-01-12
    • 2015-11-27
    • 2013-06-17
    • 2016-09-29
    • 2017-03-12
    • 2014-03-20
    • 2019-02-19
    相关资源
    最近更新 更多