需要依次调用多个api,在javascript中一个接一个

我需要在javascript中一个接一个地依次调用多个api。一个人的反应可能需要作为另一个人的输入。有人可以建议或提供示例代码。

我尝试使用 .fetch() api,但发现很难将一个 api 的响应传递给另一个。


慕标琳琳
浏览 220回答 2
2回答

德玛西亚99

利用apipromises原生返回fetch,多个请求可以一个接一个的链接var result = fetch('api/url1') // First request    .then(function (response) {        return response.json();    })    .then(function (data) {        var secondId = data.someId        return fetch('api/url2' + secondId); // Second request    })    .then(function (response) {        return response.json();    })    .then(function (data) {        var thirdId = data.someId        return fetch('api/url3' + thirdId); // Third request    })    .then(function (response) {        return response.json();    })    .then(function (data) {        // Response of third API    })    .catch(function (error) {        console.log('Error', error)    })

MMMHUHU

尽管答案已被接受,但请尝试async await这样。(async () => {  // first  const res = await fetch("https://reqres.in/api/users/1");  const result1 = await res.json();    console.log("Result 1", result1);    // some logic ...    // second   const res2 = await fetch("https://reqres.in/api/users/2");  const result2 = await res2.json();    console.log("Result 2", result2);  // ... so on ...})();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript