Axios: 複数のリクエストをチェーンする方法の例?

作成日 2017年02月15日  ·  12コメント  ·  ソース: axios/axios

最初のリクエストの結果を使用して2番目のリクエストを作成する必要がある場合など、誰かが私に例を示したり、複数のリクエストをチェーンする方法のコードスニペットを共有したりできますか?

最も参考になるコメント

結果は通常の約束であるため、連鎖させることができます。

axios.get(...)
  .then((response) => {
    return axios.get(...); // using response.data
  })
  .then((response) => {
    console.log('Response', response);
  });

全てのコメント12件

結果は通常の約束であるため、連鎖させることができます。

axios.get(...)
  .then((response) => {
    return axios.get(...); // using response.data
  })
  .then((response) => {
    console.log('Response', response);
  });

この例では、リクエストが成功した場合でも、 responseは未定義として返されますか?

いいえ、定義する必要があります。 returnステートメントに注意してください。 あなたはおそらくそれを逃したでしょう。

ayyyyy

そして、この場合、どのようにして個々のエラーをキャッチしますか?

axios投稿を送信するためのループ(for)があり、各リクエストは各ループの後に送信されておらず、ループオーバー後に一緒に送信されていることがわかりました
これは私のコードです

`
for(let i = 0; i <differ; i ++){
tem.start = moment(start).add(i、'days')。format('YYYY-MM-DD')
tem.end = moment(tem.start).endOf('day')。format('YYYY-MM-DD 23:59:59')
tem.date = tem.start
// if(V.hasSameValue(title、tem.start、tem.end))continue
V.addEventsToCalendar(tem)
}
addEventsToCalendar :(イベント)=> {
axios.post(requestUrl('calendar')、{... event})
.then(res => {
V.eventsRender(V.dataToEvent([res.data]))
successTip()
})
.catch(errorTip)
}、

`

@Liaohuanle
は非同期であるため、各操作の終了を待機しません。 ループの代わりに、単純な再帰を使用できます。

なぜこれを試してみませんか?

axios.get(...)
  .then((response) => {
    axios.get(...)
   .then((response) => {
      console.log('response);
    })
})

@alejogamboaさらに別のコールバック地獄、あなたはどう思いますか?

var array = [0,1,2];
axios.get('api/' + array[0]).then(response => {
    axios.get('api/' + array[1]).then(response => {
         axios.get('api/' + array[2]).then(response => {
            alert('done');
         });
    });
});

配列に基づいてチェーンするにはどうすればよいですか?

@jericopulveraは使用を見てみましょう
axios.all([])

for (...) {
  arr.push(axios.get("url"));
}

let result = await axios.all(arr);
console.log(res);

すでにここで解決策を得ています#1413

このページは役に立ちましたか?
0 / 5 - 0 評価