[英]Code executing in wrong order and it isn't async (I think…)
我在下面有这段代码。 为什么 console.log("done:) 在循环完成之前执行?我知道“请求”是异步的,但我的 console.log 在回调 function 内。回调 function 是同步的(据我所知)和开始遍历循环,然后当循环完成时,它应该执行我的 console.log("done")。但它没有。它在循环的第一次迭代之前(或在循环的第一次迭代之后)执行它。循环是否异步也是?这是我能解释发生了什么的唯一方法。
const request = require('request');
var item_urls;
var options = {
json: true
};
var test = [] ;
function updateDB (){
var url = "https://api.warframe.market/v1/items";
request(url, options, (error, res, body) =>{
if (error) {
return console.log(error)
};
if (!error && res.statusCode == 200) {
console.log("executing cb1");
item_urls = body.payload.items;
var primes = item_urls.filter(item => item.item_name.includes("Strun Wraith Set"));
for (item in primes) // Loop through items, then and add to recipelist. This is to make it the same name as the URL attribute.
{
let url = `https://api.warframe.market/v1/items/${primes[item].url_name}`;
// console.log (url);
request(url, options, (error, res, body) =>{
if (error) {
return console.log(error)
};
if (!error && res.statusCode == 200) {
console.log(`Getting item ${url}`);
test.push(body.payload.item);
}
});
};
console.log ("done");
};
});
}
updateDB ();
for
循环不是异步的,并且console.log("done")
确实在循环之后运行。 但是,您正在for
循环中发出异步请求,这就是为什么您之后会看到内部请求回调的console.log
的原因。
request(url, options, (error, res, body) => { ... })
即使对request
一无所知,您也可以知道这是一个异步 function 调用:它不返回结果,而是接受 function 以在所述结果上运行。
同步调用看起来像这样:
let [error, res, body] = request(url, options);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.