Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 一个接一个地取_Javascript_Ecmascript 6_Fetch - Fatal编程技术网

Javascript 一个接一个地取

Javascript 一个接一个地取,javascript,ecmascript-6,fetch,Javascript,Ecmascript 6,Fetch,我有以下代码: fetchA() { fetch(aURL) .then(response => response.json()) .then(json => { this.setState({ a: json}) }) } fetchB() { fetch(bURL) .then(response => response.json()) .then(json => { this.setState(

我有以下代码:

fetchA() {
  fetch(aURL)
    .then(response => response.json())
    .then(json => {
      this.setState({ a: json})
    })
}

fetchB() {
  fetch(bURL)
    .then(response => response.json())
    .then(json => {
      this.setState({ b: json})
    })
}
网络上的大多数教程都会教您如何等待,直到收集到A和B的响应,例如:

但我要的是取A,A完成后再取B

我怎么能这么做

谢谢你的时间

=======已编辑=======

在我的真实代码中,我尝试了:

fetchA(){
  fetch(aURL)
    .then(fetchB())
    .then(response => console.log(response))
    .then(() => console.log('hi'))
}

fetchB(){
  fetch(bURL)
    .then((response) => console.log(response))
}

// call it
this.fetchA()

// output:
//
// A data
// hi
// B data

// what I want is:
// 
// B data
// A data
// hi
你可以用它来连锁

fetch(aURL)
    .then(response = > console.log('do something'))
    .then(fetchB)
更新:别忘了纠正fetchB。它应该回报承诺


然后调用this.fetchA开始

,但我想要的是在A完成后获取A,然后获取B。如果您跳过该语句中的when,您基本上拥有需要编写的代码的文本版本。方法和顺序甚至非常接近。只是别忘了从fetchA和fetchB返回。如果我只有fetchB和fetchA,那没关系。但是如果我有fetchC呢?e、 g.:fetchaURL.then=>console.log'a'。thenfetchB.thenfetchC不能保证在fetchC之前执行fetchB,对吗?@mCY为什么要添加?如果你删除了它,对你的评论的回答将是:不,它将保证你说的是顺序。@Kevin B但我尝试了fetchaURL.thenres=>console.logres.thenfetchB.then=>console.log'hi'。但是hi出现在fetchB的输出之前…@mCY可能是因为fetchB的编码不正确。你忘了还承诺了吗?@Kevin B,另外,我发现添加或不添加都不会改变订单。fetchB返回承诺,fetchB返回函数?但是,为什么要删除这个选项呢?
fetch(aURL)
    .then(response = > console.log('do something'))
    .then(fetchB)
fetchB() {
  return fetch(bURL)
    .then(response => response.json())
    .then(json => {
      this.setState({ b: json})
    })
}
fetchA() {
  fetch(aURL)
    .then(response => response.json())
    .then(json => {
       this.setState({ a: json}, this.fetchB); //this line changed
    })
}