我需要帮助,我有 n 个数据,这些数据由 ajax 请求返回给客户端。我需要从其他应用程序调用 api 的每一行数据。现在我正在使用 callback
为此,是的,api 是成功的,并且按照我的预期提供了值(value)。但是我遇到了一些小问题。我有每天访问 api 的数量限制,所以我想要的是 callback
对于 api 正在响应一些 error_code
喜欢out of quota
或任何错误代码,因此对于下一行数据我不想再次调用 api。我的代码如下:
$("#verifyMe").submit(function(event) {
var isError = false;
var formDatas = new FormData($('#verifyMe')[0]);
// getting my row Data (SELECT * FROM table)
$.ajax({
....
success: function(kis) {
for (var i = 0; i < kis.data.length; i++) { // loop as many row data
// call api as long as no break
console.log(isError); // always be false
checking(kis.data[i].id, function(output){ // api returning object
if(output.error_code) {
console.log(isError); // last value
isError = true; // only affect in callback bracket
console.log(isError); // true
break; // break for loop calling the api
}
} // end of callback bracket
// I think the break; should goes this line but error_code will undefined bc out of callback function
}
}
});
});
我认为问题是因为异步。 error_code
在 callback
永远undefined/null
从那个callback
, 和 break;
如果它在 for loop
中将会起作用括号(在示例代码中,我显示它在 callback
括号中)。对不起,如果我的解释不够清楚。谢谢
最佳答案
您可以使用 Promise.each() 轻松实现您的要求 bluebird 图书馆。 使用此函数,您可以顺序执行异步函数。
var Promise = require('bluebird');
...
$.ajax({
....
success: function(kis) {
Promise.each(kis.data, (oneData) => {
return new Promise((resolve, reject) => {
// It will be performed sequentially
checking(oneData.id, function(output){ // api returning object
if(output.error_code) {
reject(output.error_code); // break for loop calling the api
}
// Success case
resolve();
});
});
})
.then(result => {
// Will be called when all kis.data have been successfully processed
})
.catch(error => {
// Will be called when an error occurs in the kid.data
});
}
}
});
关于javascript - 回调为 num_rows 并在语句满足时中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62868385/