如何同步執行 HTTP 請求并使用 Javascript 將結果存盤在本地物件中?
給定以下 javascript 模塊:
var Promise = require("promise");
function myReq(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = 'json';
xhr.onload = () => {
if (xhr.status >= 400){
console.log("got rejected");
reject({status: xhr.status, statusText: xhr.statusText});
} else {
console.log("resolved");
resolve({data: xhr.response});
}
};
xhr.onerror = () => {
console.log("Error was called");
reject({status: xhr.status, statusText: xhr.statusText});
};
xhr.send();
});
}
export default myReq;
我希望將此請求中的 json 物件存盤在另一個腳本的區域變數中。但是,當我嘗試此代碼時,它會異步運行它。
1. import myReq from '../../lib/myReq';
2. const urlTest = "localhost://3000:/somepath";
3. const test = myReq(urlTest).then((a) => {console.log(a); return a;}).catch((b) => console.log(b));
4. console.log(test.data);
我希望它在第 3 行停止,執行代碼,將 javascript 物件存盤在測驗中,然后繼續執行其余代碼。現在 test 是一個 Promise 并且 test.data 是未定義的。
uj5u.com熱心網友回復:
myReq回傳一個 Promise,而不僅僅是資料!這就是為什么您需要使用then&catch塊,或者使用await.
// myReq function returns a Promise, NOT a value! (Not returning 5!)
function myReq(url) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(5);
}, 5000);
});
}
// Option 1
myReq('someurl').then((data) => {
console.log('data (option 1)', data); // You can use the data here, inside the 'then' block
}).catch((error) => {
console.log('error', error);
});
// Option 2
const run = async () => {
try {
const data = await myReq('someurl'); // await must be called from an 'async' function
console.log('data (option 2)', data); // You can use the data here, inside the 'try' block
} catch (error) {
console.log('error', error);
}
};
run();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/477781.html
標籤:javascript 异步 承诺 xmlhttp请求
