我是第一次在 JS 中實作 Promises 并且在運行以下代碼時在控制臺日志中未捕獲到 promise 例外。
function data_present() {
return new Promise((resolve, reject) => {
fetch(api)
.then(response => response.json())
.then(message => {
console.log(message)
if(message && Object.keys(message).length != 0) {
resolve()
}
else {
reject()
}
})
})
}
我正在主函式中處理 promise 回傳值的結果,如下所示,但尚未捕獲到 promise 訊息:
function main() {
data_present().then(() => {
load_graph()
}).catch(() => {
data_present()
})
}
data_present() 背后的邏輯是等待,直到我們在 API 端點獲得非空 JSON 回應,如果 JSON 回應為空,則繼續輪詢它。
我得到的例外如下:
Uncaught (in promise) undefined
(anonymous) @ index.js:34
Promise.then (async)
(anonymous) @ index.js:29
data_present @ index.js:26
(anonymous) @ index.js:56
Promise.catch (async)
getParametersData @ index.js:55
onclick @ (index):92
uj5u.com熱心網友回復:
您可能會考慮使用一個函式來從 API 獲取、決議和回傳 JSON(無需將您fetch的承諾包裝在承諾中,因為它已經回傳一個),并使用您的輪詢函式來檢查回傳的資料。如果正確呼叫一個函式,否則getData再次輪詢。如果有一個 API 錯誤日志。
我在async/await這里用過,但原理是一樣的。
// Simulates an API
// If the random number is a modulo of 5 set data
// to an object with a key/value pair, otherwise
// it set it to an empty object. If the random number
// is a modulo of 9 send an error, otherwise send the data.
function mockFetch() {
return new Promise((res, rej) => {
const rnd = Math.floor(Math.random() * 20);
const data = rnd % 5 === 0 ? { name: 'Bob' } : {};
setTimeout(() => {
if (rnd % 9 === 0) rej('Connection error');
res(JSON.stringify(data));
}, 2000);
});
}
// `getData` simply gets a response from the API and parses it.
// I had to use JSON.parse here rather that await response.json()
// because I'm not using the actual fetch API.
async function getData() {
const response = await mockFetch();
return JSON.parse(response);
}
// The `poll` function does all the heavy-lifting
// first we initialise `count`
async function poll(count = 1) {
console.log(`Polling ${count}`);
// Try and get some data. If it's not an empty object
// log the name (or in your case call loadGraph),
// otherwise poll the API again after two seconds.
// We wrap everything in a `try/catch`.
try {
const data = await getData();
if (data && data.name) {
console.log(data.name); // loadGraph
} else {
setTimeout(poll, 2000, count);
}
// If the API sends an error log that instead
// and poll again after five seconds
} catch (err) {
console.log(`${err}. Polling again in 5 seconds.`);
setTimeout(poll, 5000, 1);
}
}
poll();
uj5u.com熱心網友回復:
也fetch已經回傳了一個承諾。所以你不應該再包裝它(我在我的例子中包含了這個)。錯誤來自對函式的第二次呼叫,如下面的第二個 catch 塊中所述
function data_present() {
return fetch(api)
.then(response => response.json())
.then(message => {
console.log(message)
if (!message || Object.keys(message).length === 0) {
throw new Error('something went wrong');
}
})
}
function main() {
data_present()
.then(() => {
load_graph()
}).catch(() => {
return data_present() // the promise which is returned here was not caught in your example
})
.catch(() => {
// another error
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/395454.html
標籤:javascript json 承诺
上一篇:引數物件
