js:一段时间内的承诺 - 真正的循环

时间:2018-06-11 20:40:30

标签: javascript asynchronous promise youtube-api

我在从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

2 个答案:

答案 0 :(得分:1)

我认为您可以使用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;
}

答案 1 :(得分:1)

您遇到的问题是循环是同步的,但nextPageToken的赋值是异步的。我实际上不确定,但这样的工作会使用递归

structure(list(id = c(101L, 101L, 101L, 101L, 102L, 102L, 102L, 
102L, 103L, 103L, 103L, 103L, 103L, 103L, 103L, 104L, 104L, 104L, 
104L, 104L, 105L, 106L, 106L, 106L, 106L, 106L, 107L, 107L, 107L, 
107L, 108L, 108L, 109L, 109L, 109L, 109L, 109L, 109L, 109L, 109L, 
109L, 109L), resource = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L), .Label = c("a", "b"), class = "factor"), result = c(2.12, 
4.72, 4.17, 5.53, 3.6, 3.31, 3.64, 5.33, 4.32, 5.48, 5.93, 3.4, 
3.09, 5.91, 2.93, 1.81, 3.93, 2.22, 4.77, 3.92, 4.08, 3.65, 5.23, 
3.74, 4.03, 3.54, 4.29, 4.3, 2.82, 2.89, 5.41, 4.61, 4, 5.92, 
1.66, 1.65, 1.91, 2.69, 5.28, 2.24, 3.64, 4.77), live = structure(c(2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 
1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L), .Label = c("f", "t"), class = "factor")), class = "data.frame", row.names = c(NA, 
-42L))