我花了一些時間試圖理解這一點。我希望答案是顯而易見的,只是表明我缺乏經驗
我的目標是向 Steam 發送各種游戲模組 ID 的 API 請求,并找到每個模組的 time_updated,將它們全部放入一個陣列中,然后找出最近更新的那個
我有下面的代碼,但它并沒有完全按照我的意愿行事,我想我只是對時間感到困惑
我的計劃是在 arrMODID = [] 中有幾個不同的值,并遍歷每個值,獲取 time_updated,將其推送到一個陣列,以便const result = await myfunction();能夠訪問modinfoArray
然而,它正在回傳一個只包含其中的陣列,[{test},{}]并且在函式將任何資料放入陣列之前被觸發
誰能給我一個正確的方向,請
謝謝你
import request from 'request';
const myfunction = async function(x, y) {
var arrMODID = ["2016338122"];
var modinfoArray = []
var timeUpdated
for (const element of arrMODID) {
request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://api.steampowered.com/ISteamRemoteStorage/GetPublishedFileDetails/v1',
body: 'itemcount=1&publishedfileids[0]=2016338122',
},
function(error, response, body){
var response = JSON.parse(body);
var myResponse = response.response.publishedfiledetails
myResponse.forEach(function(arrayItem) {
//console.log(arrayItem.time_updated)
timeUpdated = arrayItem.time_updated
//console.log(timeUpdated)
modinfoArray.push({"2016338122":arrayItem.time_updated})
console.log(modinfoArray) // only this log returns the added items
})
});
}
return ["test", modinfoArray];
};
// Start function
const start = async function(a, b) {
const result = await myfunction();
console.log(result); // this returns the empty array
}
// Call start
start();
uj5u.com熱心網友回復:
您需要使用支持承諾的 http 請求庫,以便您可以await在您的函式中使用它。您不能像request.post()使用普通回呼那樣成功地混合使用 Promise 和異步操作,因為您可以使用普通回呼以類似 Promise 的方式管理控制流。
我建議使用got()圖書館。此外,該request()庫已被棄用,不推薦用于新代碼。如果您絕對想繼續使用該request()庫,則可以改用該request-promise模塊,但請記住,該request()庫僅處于維護模式(沒有新功能開發),而此替代方案串列都在積極開發中。
這是使用got()庫的可運行實作:
import got from 'got';
const myfunction = async function() {
const arrMODID = ["2016338122"];
const modinfoArray = [];
for (const element of arrMODID) {
const response = await got.post({
headers: { 'content-type': 'application/x-www-form-urlencoded' },
url: 'http://api.steampowered.com/ISteamRemoteStorage/GetPublishedFileDetails/v1',
body: 'itemcount=1&publishedfileids[0]=2016338122',
}).json();
const myResponse = response.response.publishedfiledetails;
for (const arrayItem of myResponse) {
modinfoArray.push({ "2016338122": arrayItem.time_updated });
}
}
return ["test", modinfoArray];
};
// Start function
const start = async function() {
const result = await myfunction();
console.log(result);
return result;
}
// Call start
start().then(result => {
console.log("done");
}).catch(err => {
console.log(err);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/350396.html
標籤:节点.js
