Web Fetch API(等待fetch完成,然后执行下一条指令)

Web Fetch API (waiting the fetch to complete and then executed the next instruction)

是否可以等到'Fetch'指令完成后再执行下一个code/instruction?? (就像 AJAX 等待的工作原理一样)

这些函数实际上是用来从 Facebook Graph API 请求 'privacy value' of post,但是,我怎么 运行 alert 提示框直到 "EVERYTHING" 结束了 (FirstRequestToGraph + RequestNextPage )

FirstRequestToGraph(AccessToken)
.then(function() {
      RequestNextPage(NextPage); //recursively until there's no more next page
})
.then(function() {
      alert("everything have ended nieely"); //still pop up before RequestNextPage Completed 
});

_

function RequestNextPage(NextPage){
      fetch(NextPage, {
        method: 'GET'
      })
     .then(function(response) {
         return response.json();
      })
      .then(function(json) {
          if(json.data.length == 0 ){
           console.log("ended liao lur");
       }else{
           RequestNextPage(json.paging.next);
       }
      })
     .catch(function(err) {
         console.log(`Error: ${err}` )
      });
}

_

function FirstRequestToGraph(AccessToken){
      fetch('https://graph.facebook.com/v2.8/me?fields=posts.limit(275){privacy}%2Cname&access_token='+AccessToken, {
    method: 'GET'
  })
  .then(function(response) {
    return response.json();
  })
  .then(function(json){
    NextPage = json.posts.paging.next;
  })
  .catch(function(err) {
    console.log(`Error: ${err}` )
  });

}
FirstRequestToGraph(AccessToken).then(function() {
    alert('testing1234');
});

function RequestNextPage(NextPage) {
    return fetch(NextPage, {
        method: 'GET'
    })
    .then(function(response) {
        return response.json();
    })
    .then(function(json) {
        RequestNextPage(json.paging.next);
    })
    .catch(function(err) {
        console.log(`Error: ${err}`)
    });
}

function FirstRequestToGraph(AccessToken) {
    return fetch('https://graph.facebook.com/v2.8/me?fields=posts.limit(275){privacy}%2Cname&access_token=' + AccessToken, {
        method: 'GET'
    })
    .then(function(response) {
        return response.json();
    })
    .then(function(json) {
        if(json.data.length !== 0 ){
           return RequestNextPage(json.paging.next);
        }
    })
    .catch(function(err) {
        console.log(`Error: ${err}`)
    });
}

如果你的组件中有一个异步函数,像这样...

async getJSON() {
    return fetch('/website/MyJsonFile.json')
        .then((response)=>response.json())
        .then((responseJson)=>{return responseJson});
}

然后你可以调用它,等待它下载,使用 await 命令,使用类似这样的东西...

async caller() {
    const json = await this.getJSON();  // command waits until completion
    console.log(json.hello);            // hello is now available
}

您还需要将 getJSON(),return fetch() 更新为 return await fetch()

async太棒了。 await.

也是

查看:Mozilla Developer Network: Async Function