[英]How do I separate the json objects in a get http request in a $scope?
[英]How to request multiple API data to convert into json and do stuff to match the separate json files
所以我有2個API鏈接,我想從https:// some_url / users和https:// some_url / posts獲取一些數據。
我想將/ users中的某些數據與/ posts進行匹配,但是如何同時從兩者中獲取數據
我知道如果我只想從/ users中獲取發言權,我會去
fetch('https://some_url/users')
.then(function(response){
return response.json();
})
.then(function(Data_users){
do stuff to Data_users
}
但是我想同時對/ users數據和/ posts數據做一些事情,所以我想從/ users和/ posts兩者中獲取並像這樣操作它們
.then(function(Data_users, Data_posts){
do stuff to Data_users and Data_posts
}
我該怎么做? 我需要一個諾言嗎?
抱歉,如果我真的不好解釋,我對javascript很陌生。
您可以使用Promise.all()
將其存檔
var userPromise = fetch('https://some_url/users').then(response => response.json());
var postPromise = fetch('https://some_url/posts').then(response => response.json());
Promise.all([userPromise, postPromise]).then(([Data_users, Data_posts]) => {
...
});
最后一個函數中兩個變量的括號是必需的,因為Promise.all
使用數組調用該函數。 使用方括號,我們可以將數組分解為兩個不同的變量。 如果沒有括號,則需要以下代碼:
....then((values) => {
var Data_users = values[0];
var Data_posts = values[1];
}
使用Promise.all,它將在數組中返回兩個結果,然后可以用來比較結果。
我們可以在這里使用async await,使用async await將使代碼更具可讀性和結構化。
const fetch = require('node-fetch');
const run = async () => {
const [users_res, posts_res] = await
Promise.all([fetch('https://reqres.in/api/users?page=2'),
fetch('https://reqres.in//api/users/2')]);
console.log(users_res, posts_res);
// we can compare users_res and posts_res here.
}
run()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.