执行执行提取的顺序函数

时间:2018-10-14 14:36:15

标签: javascript asynchronous

我需要按顺序执行handleCursor。我怎样才能做到这一点?

handleCursor正在发出获取请求,并且看起来像在获取api请求和WriteData完成之前返回的一样。我发现“修复它”的唯一方法是将所有内容都放在一个大函数中,但这看起来非常丑陋。

 function Fill(cursor, diff ){
  for (var i = 0; i < diff; i++) {
        // get the latest html htmlNode written by WriteData
        let htmlNode = document.querySelect("lastCursorElem");
        const cursor = cursorHistory.top.pop(); 
       try{
          handleCursor(cursor, htmlNode);
       }
       catch(err) { 
        console.log(err);
        return;
      } 
   }
   return;
};

function handleCursor(cursor, htmlNode){ 
   fetch(cursor).then(
    function(response) {
      switch (response.status) {
        case 200:
          response.text().then(function(data) { 
            var next = response.headers.get("next");
            WriteData(next, data, htmlNode) ;
            return;
          }).
            catch(function(err) {
              console.log('Fetch Error :-S', err);
            });
          break;
        default:
          return;
      }
    }
  ).
    catch(function(err) {
      console.log('Fetch Error :', err);
    });
}

1 个答案:

答案 0 :(得分:0)

也许是这样(未经测试):

async function Fill (cursor, diff) {
  for (var i = 0; i < diff; i++) {
    // get the latest html htmlNode written by WriteData
    const htmlNode = document.querySelector('lastCursorElem')
    const cursor = cursorHistory.top.pop() 

    try {
      const response = await fetch(cursor)
      const data = await response.text()

      if (res.ok) {
        WriteData(response.headers.get('next'), data, htmlNode)
      } else {
        console.log('response was not 200-299')
      }
    } catch (err) { 
      console.log(err)
    } 
  }
}