foreach 循环,承诺在第一个完成后执行 API 调用
foreach loop with promise execute API call AFTER the first one is done
let array = [1,2,3];
array.forEach(function(item,index) {
var data = fetch('https://reqres.in/api/products/'+item);
//wait for response after response come then next iterating a loop (first,second,third)
});
我想运行喜欢
- 第一次通话api
- 等待回复
- 显示成html
但目前我的脚本调用了所有三次 api 没有等待响应
我想等待响应,完成后调用下一个 api ..就像那样
使用 for of 而不是 forEach 循环并为这样的请求做出承诺
var items = [1, 2];
function makeRequest(index) {
return new Promise((resolve, reject) => {
$.ajax({
url: "https://reqres.in/api/products/"+index,
type: "GET",
success: function(response){
console.log(response.data);
resolve(response);
},
error: function (error) {
reject(error)
}
})
})
}
async function runAsync(locations){
for(let location of locations){
console.log('value ' + location);
await makeRequest(location);
};
}
runAsync(items);
async function asyncExample() {
let array = [1,2,3];
for (let i = 0; i < array.length; i++) {
var data = await fetch('https://reqres.in/api/products/'+item);
});
}
您必须使用 Async/Await 让代码等待 API 调用。 Async/await 无法与循环一起正常工作,为避免出现问题,您应该使用普通的 for
或 for of
。更多示例:https://zellwk.com/blog/async-await-in-loops/
您需要同步 $http 调用。 Javascript 可以通过 Promises 做到这一点。
var promise = new Promise(function(resolve, reject){ resolve("OK");});
let array = [1,2,3];
array.forEach(function(item,index) {
promise.then(
$http.get('https://reqres.in/api/products/'+item)
).then(function (response){
...
});
});
promise.catch(function(response) {
...
});
let array = [1,2,3];
array.forEach(function(item,index) {
var data = fetch('https://reqres.in/api/products/'+item);
//wait for response after response come then next iterating a loop (first,second,third)
});
我想运行喜欢
- 第一次通话api
- 等待回复
- 显示成html
但目前我的脚本调用了所有三次 api 没有等待响应
我想等待响应,完成后调用下一个 api ..就像那样
使用 for of 而不是 forEach 循环并为这样的请求做出承诺
var items = [1, 2];
function makeRequest(index) {
return new Promise((resolve, reject) => {
$.ajax({
url: "https://reqres.in/api/products/"+index,
type: "GET",
success: function(response){
console.log(response.data);
resolve(response);
},
error: function (error) {
reject(error)
}
})
})
}
async function runAsync(locations){
for(let location of locations){
console.log('value ' + location);
await makeRequest(location);
};
}
runAsync(items);
async function asyncExample() {
let array = [1,2,3];
for (let i = 0; i < array.length; i++) {
var data = await fetch('https://reqres.in/api/products/'+item);
});
}
您必须使用 Async/Await 让代码等待 API 调用。 Async/await 无法与循环一起正常工作,为避免出现问题,您应该使用普通的 for
或 for of
。更多示例:https://zellwk.com/blog/async-await-in-loops/
您需要同步 $http 调用。 Javascript 可以通过 Promises 做到这一点。
var promise = new Promise(function(resolve, reject){ resolve("OK");});
let array = [1,2,3];
array.forEach(function(item,index) {
promise.then(
$http.get('https://reqres.in/api/products/'+item)
).then(function (response){
...
});
});
promise.catch(function(response) {
...
});