鍍金池/ 問答/網(wǎng)絡(luò)安全  HTML/ for循環(huán)中的async問題

for循環(huán)中的async問題

async function getTitle(url) {
    let response = await fetch(url);
    let html = await response.text();
    return html.match(/<title>([\s\S]+)<\/title>/i)[1];
  }
  for(let i=0;i<2;i++){
    let urls = `https://tc39.github.io/ecma262/`
    !async function(){
      let result = await getTitle(urls).then(function(title){
        console.log('22222',title,i)
        return title
      })
      console.log(result)
    }()

  }```
實(shí)際運(yùn)行結(jié)果是,同時(shí)發(fā)生了兩個(gè)請求,然后等待請求接過返回后,打印結(jié)果

![clipboard.png](/img/bVbdCHI)
想期望是請求完第一個(gè)接口,并且成功返回后,再請求第二個(gè)接口請求
回答
編輯回答
傻叼

拋磚引玉。

async function getTitle(url) {
  let response = await fetch(url);
  let html = await response.text();
  return html.match(/<title>([\s\S]+)<\/title>/i)[1];
}
(async function () {
  for (let i = 0; i < 2; i++) {
    let urls = `https://tc39.github.io/ecma262/`

    let result = await getTitle(urls).then(function (title) {
      console.log('22222', title, i)
      return title
    })
    console.log(result,Date.now())
  }
})()
2017年1月28日 17:58
編輯回答
枕邊人

那你在第一個(gè)獲取數(shù)據(jù)并處理后調(diào)用第二個(gè)請求啊。(需要調(diào)整你的處理邏輯),類似

i=0;
function abc(x){
    let result = await getTitle(urls).then(function(title){
    console.log('22222',title,i)
    i++;
    if(i<x) abc(x);
    return title
}
abc(3);
2018年6月11日 14:01