function fakeRequest(url) {
return new Promise((resolve, reject) => {
delay = Math.floor(Math.random() * 4500) + 500;
setTimeout(() => {
if (delay > 4500) {
resolve(url + ": success")
}
else {
reject(url = ": error")
}
}, delay);
})
})
}
async function makeTwoRequests() {
let data1 = await fakeRequest("/page1");
console.log("Data 1:", data1)
let data2 = await fakeRequest("/page2");
console.log("Data 2:", data2)
}
makeTwoRequests()
When I remove data1 or data2 and just have 1 await it works. But when there are 2 or more it errors out saying: Uncaught (in promise) : error
I don't know what's happening here. Please help me out
Thanks!
If you await a promise that rejects, it becomes a thrown error.
Change the reject inside fakeRequest to a resolve and I bet the problem goes away.
This works for me:
function fakeRequest(url) {
return new Promise((resolve, reject) => {
let delay = Math.floor(Math.random() * 4500) + 500;
setTimeout(() => {
if (delay > 4500) {
resolve(url + ": success")
} else {
resolve(url + ": error")
}
}, delay);
})
}
async function makeTwoRequests() {
let data1 = await fakeRequest("/page1");
console.log("Data 1:", data1)
let data2 = await fakeRequest("/page2");
console.log("Data 2:", data2)
}
makeTwoRequests()
There were a couple other issues with the sample code:
delay ought to be declared with a keyword like let, const, or var; this is necessary to guarantee that each invocation of the function uses its own private version instead of a shared one, and to prevent this function from changing variables in the outer scopereject call uses = instead of +, which redefines and returns the url variable instead of concatenating the URL string with the literal : error string}), which prevented this code from parsingBut I think I get what you're up to: you're trying to simulate a situation in which API calls usually succeed, except for some that fail by timing out.
Your fakeRequest does accomplish that, but your calling code isn't capable of handling the problem. For that, you'd need something like this:
async function makeTwoRequests() {
let data1
try {
data1 = await fakeRequest("/page1");
} catch ( error ) {
console.error(`request 1 threw`, error)
// here, you might return, or re-throw, or fall through
}
let data2
try {
data2 = await fakeRequest("/page2");
} catch ( error ) {
console.error(`request 2 threw`, error)
// here, you might return, or re-throw, or fall through
}
}