Promise and one strange behaviour [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 days ago.
Improve this question
I encountered a strange behavior when I defined 4 Promises which the last one is described as just rejected and when I tried to run each promise separately, the last one is fired! This will fire rejection especially when I want to run all Promises (_1 _2 _3) in Promise.all().
I wanted to use catch() for promise_2 in Promise.all([promise.catch((err)=>console.log(err))]).then(...) from handling the error happend in promise_2 without cancelling the operation of other Promises
Thx
const asyncFunction=(timer,callback)=>{
setTimeout(() => {
callback(10)
}, timer);
}
const promise_1=new Promise((resolved,reject)=>{
const date=new Date().getSeconds()
date%2===0?asyncFunction(1000,(value)=>resolved(value)):reject(new Error("hello"))
})
const promise_2=new Promise((resolved,reject)=>{
asyncFunction(2000,(value)=>resolved(value))
})
const promise_3=new Promise((resolved,reject)=>{
asyncFunction(3000,(value)=>resolved(value))
})
const promise_4=new Promise((resolved,reject)=>{
reject(new Error("i am bad"))
})
promise_1.then((value)=>console.log(value))
first in Node
C:\Program Files\nodejs\node.exe .\test.js
Process exited with code 1
Uncaught Error Error: I am bad<--------------------------what is it?this is for promise_4 ,while I didn't call it
second in V8
See here
[in V81

Related

Javascript setTimeout handle promise rejection [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 13 days ago.
Improve this question
Im currently trying to make a timeout for a function
setTimeout(() => function_name(), 10000)
This function may raise an exception or reject a promise
How do I handle a rejection in this case ?
Im unsure of what to try
Just wrap it in a try/catch
setTimeout(() => {
try {
function_name();
} catch (err) {
console.log(err);
}
}, 10000);

Having issues getting data from api call [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
Hey guys Im making a api call and getting a response I have not yet encountered . my api call is basic and looks like
async function getStudents(){
const response = await fetch('url');
const studentData = response.json();
console.log(studentData)
Promise { : "pending" } : "fulfilled" : Object {
students: (25) […] }
and these are the results I get, Normally I could do something like studentData.students to get that object but nothing seems to get the correct object. what am I doing wroing?
Use something like this :
async function getStudents(){
fetch('url')
.then(response => response.json())
.then(data => console.log(data));
.catch(error=>console.log(error,"error occured"));
}

Is Nesting Promises Bad Practice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I know my code has the correct logic, but everywhere I look I'm told not to use nested promises. Is this a use case for nested promises?
The logic is as follows:
promise1 fails -> reverse promise1
promise1 succeeds -> promise2/promise3 fails -> reverse promise1,
promise2, promise 3
promise1 succeeds -> promise2 & promise3 succeeds
let data = null;
promise1.then((response) => {
data = response;
return Promise.all([promise2(), proimse3()])
.catch((error) => {
//Reverse only promise2, promise3
//Throw error to reverse promise1
});
}).then((id) => {
something(data);
}).catch((error) => {
//Reverse only promise1
});

What prommaing obstacle do JavaScript Promises solve? Or what ARE they, exactly? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I've been programming in JavaScript for a couple years and never heard the term Promise until recently. I've read multiple articles on the web about it and still don't understand what a Promise is. I don't see any rigorous definition. Every example I've seen is of a problem I've already known how to solve. For example,
get('story.json').then(function(response) {
console.log("Success!", response);
}, function(error) {
console.error("Failed!", error);
});
from https://davidwalsh.name/promises I would've already known how to do like
$.ajax({
url : 'story.json',
method : 'GET',
success : function(response) { console.log("Success!", response); },
error : function(error) { console.error("Failed!", error); }
});
So was I using the concept of a Promise without knowing the term? Or where's the big party that I'm missing out on?
The addition is being able to chain things.
If you need to make three calls which all have to happen one after the other, you can chain your promises together rather than:
$.ajax({
success () {
$.ajax({
success () {
$.ajax({
success () { /* do something with your sets of results */ }
});
}
});
}
});
instead, you can do something like:
fetch(url1).then(toJSON)
.then(result1 => fetch(url2).then(toJSON))
.then(result2 => fetch(url3).then(toJSON));
These two examples aren't doing exactly the same thing (you'd need to use each result, or pass it out, to pass it on), but basically promises wrap your process and return you an object (with a .then method) which allows you to add callbacks (and keep adding them).

How can I queue and execute multiple promises asynchronously with a single callback? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am using the http request library got. With this package, http connections are asynchronous, fast, and easy to type out. The "got"cha is that got is a promisified package, which brings up several challenges for me. One is that I don't know how to pass around a reference to the got.
What I need to do is use got together with file streams to download the page contents of several url's. Upon completion of all of these streams, I want to continue in the code.
In this example instead of making an array of promises I am getting an array of response objects.
const getFile = (fileUrl) => {
return new Promise((resolve) => {
got.stream(fileUrl).pipe(fs.createWriteStream(path.basename(fileUrl)))
.on('finish', () => {
successMessage('downloaded ' + fileUrl + '!');
resolve();
});
});
};
// create an array of these got promises
let promises = []
for (let file of body.files) {
promises.push(getFile(file));
}
The reason the getFile helper exists is to wrap the got in a promise so that after performing all of the gots, I can use a promise.all call:
// after all got's have executed
promises.all(promises).then(() => {
console.log('all promises resolved');
}
Looking for assistance understanding how to change the first snippet so that promises.all behaves as anticipated.
The Promise aggregation function is called Promise.all() not promises.all().

Categories

Resources