[英]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.