在提取语句中连续调用两个函数

时间:2018-11-23 15:25:07

标签: javascript

我有两个带有提取调用的功能。当我在具有提取语句的第三函数中连续调用它们时。只有一个被呼叫,另一个未被呼叫。

reloadOne() {
fetch(...)
...
return;
}

reloadTwo() {
    fetch(...)
    ...
    return;
    }

myOtherFunction()
{
fetch(...).then((res) => { return this.reloadOne(); }).then((res) => { return this.reloadTwo(); }))
}

1 个答案:

答案 0 :(得分:1)

您需要返回fetch方法,以便它们返回的诺言可以兑现。

请参见以下示例:https://jsbin.com/fijohanoge/edit?js,console

function functionOne() {
  console.log('function 1');
  return fetch("https://null.jsbin.com")
  .then(() => {
    console.log('function 1 result');
  })
  .catch((err) => {
    console.error(err);
  });
}

function functionTwo() {
  console.log('function 2');
  return fetch("https://null.jsbin.com")
  .then(() => {
    console.log('function 2 result');
  })
  .catch((err) => {
    console.error(err);
  });
}

console.log('start');
fetch("https://null.jsbin.com")
.catch((err) => { console.error(err); })
.then((res) => {
  console.log('response 1');
  return functionOne();
})
.then(() => {
  console.log('before function 2');
  return functionTwo();
})
.then(() => {
  console.log('after function 2');
  return;
})