取后续

时间:2017-05-25 16:56:41

标签: ecmascript-6 fetch

代码如下:

var fetch = require('node-fetch')

function fetchA(){
  fetch('https://github.com/keegoo')
    .then(response => console.log('fetchA'))
    .then(fetchB)
    .then(fetchC)
    .then(() => console.log('hi'))
}

function fetchB(){
  fetch('https://github.com/keegoo/trigger')
    .then(response => console.log('fetchB'))
}

function fetchC(){
  fetch('https://github.com/keegoo/trigger/tree/master/app')
    .then(response => console.log('fetchC'))

}
// call 
fetchA()

在fetchA中,我调用了fetchB和fetchC。

我期待输出应该是:

fetchA
fetchB
fetchC
hi

相反,它是:

fetchA
hi
fetchC
fetchB 

为什么呢?

如果我需要输出为fetchA -> fetchB -> fetchC -> Hi,我该怎么办?

2 个答案:

答案 0 :(得分:1)

您的 {% load cms_tags %} {% for obj in object %} {% render_placeholder obj.my_placeholder "640" %} {% endfor %} fetchB应该返回fetchC的承诺,否则会立即解决fetch之类的后续呼叫。

.then(fetchB)

答案 1 :(得分:0)

您需要返回承诺 !!!

在了解原因之前,您需要了解以下两个事实。

  1. 承诺的返回值(此处为then)将传递给下一个承诺(下一个then)。
  2. Promise.resolve('A')
      .then(x => {
        console.log(x)  // output A
        return 'B'
      }) 
      .then(x => {
        console.log(x)  // output B
                        // no return here !
      })
      .then(x => {
        console.log(x)  // output undefined, cause the **previous** `then` didn't return anything
        return 'C' 
      })
      .then(x => {
        console.log(x)  // output C
        return 'D'
      })// promise chain goes on ...

    1. 承诺链,例如fetch().then().then().then() ...,将立即返回。
    2. // here blockA simulate a heavy operation: 3000 ms later, 'A' will be returned.
      const blockA = new Promise((resolve, reject) => setTimeout(() => resolve('A'), 3000))
      
      blockA
      .then(x => {
        console.log(x)
        return 'B'
      })
      .then(x => {
        console.log(x)
        return 'c'
      }) // chains goes on ...
      
      console.log('Hello world')

      无论承诺链有多长,'Hello world'总是先输出,这意味着承诺链会立即返回。在稍后解决blockA之前,将执行以下then(回调)。

      在你的情况下:

      fetchBfetchC会立即返回,对吧?

      function fetchA(){
        fetch('https://github.com/keegoo')
          .then(response => console.log('fetchA'))  // when 'https://...' responded, this promise been execute, output fetchA
          .then(fetchB)   // then fetchB be executed, but return immediately.
          .then(fetchC)   // then fetchC be executed, but return immedidately again.
          .then(() => console.log('hi'))  // then output 'hi'
      }
      
      // sometime in the future, when the `fetch`s inside fetchB and fetchC got responses, the `console.log`s then be executed.
      

      因此,如果您return fetch().then().then(),承诺链将被买入下一个承诺,并且会在继续之前完全解决。