I'm using blockexplorer API for blockchain, and I want to get block data based on specific hash (This hash should be taken from another function).
I'm new with using Promise, So can anyone help me to get the block data?
This is my code:
const be = require('blockexplorer');
be.block(be.blockIndex(0))
.then((result) => {
console.log(result)
})
.catch((err) => {
throw err
})
Also, I've tried another way with using nested Promise but it didn't work.
You can make a promise.then return a promise and chain it further. Modify the code to this.
be.blockIndex(0)
.then((result) => be.block(result))
.then((result) => {
console.log(result)
})
.catch((err) => {
console.log("Error Occurred: ", err); // Don't throw the error instead handle it
});
Related
I am trying to add a new user with firebase-admin and then to save a new document in a custom collection.
Sample code following:
admin.auth().createUser(user)
.then((record) => {
user.uid = record.uid;
userCollection.doc(record.uid).set({...user})
.then(writeResult => {
resolve();
})
.catch(reason => {
reject(reason)
});
})
.catch((err) => {
reject(err);
});
The problem is, if the userCollection.doc(record.uid).set({...user}) fails, I expect the nested catch (with reason as param) to be called. Instead, always the outer one is called (with err as param).
Is there something wrong with the SDK or am I doing something wrong?
Thank you
This is because you don't return the promise returned by userCollection.doc(record.uid).set() and therefore you don't return the promises returned by the subsequent then() and catch() methods. In other words you don't return the promises chain.
But, actually, you should chain your Promises as follows and avoid a then()/catch() pyramid.
admin
.auth().createUser(user)
.then((record) => {
user.uid = record.uid;
return userCollection
.doc(record.uid)
.set({ ...user })
})
.catch((err) => {
// Here you catch the potential errors of
// the createUser() AND set() methods
console.log(JSON.stringify(err));
});
More details here, here and here.
I want to call this api multiple times in my project and when I am calling it , It continues giving an error which is
TypeError: Failed to execute 'json' on 'Response': body stream already
read at main.js:Line number
My Code is as Follows
let thisIsUrl = 'https://api.covid19api.com/summary';
let a = fetch(thisIsUrl)
a.then((data) => {
return data.json()
}).then((apidata) => {
console.log(apidata)
return apidata
}).catch((error) => {
console.log(error)
})
a.then((fetchdata) => {
return fetchdata.json()
}).then((readingData) => {
console.log(readingData)
}).catch((err) => {
console.log(err)
})
You're not calling fetch multiple times. You're calling it once, and then trying to read the response body multiple times. That's why the error says you're trying to read the body when the stream is already closed — it was closed when you were done reading it the first time.
If you want to use the data twice, store it somewhere and use it twice.
let thisIsUrl = 'https://api.covid19api.com/summary';
let a = fetch(thisIsUrl)
a.then((data) => {
return data.json()
}).then((apidata) => {
// **************** Use it twice here
}).catch((error) => {
console.log(error)
})
If you want to fetch it again because it may have been updated, call fetch again:
let thisIsUrl = 'https://api.covid19api.com/summary';
fetch(thisIsUrl)
.then((data) => {
return data.json();
}).then((apidata) => {
console.log(apidata);
return apidata;
}).catch((error) => {
console.log(error);
});
// Presumably this is later (in time), not immediately after the above
fetch(thisIsUrl)
.then((fetchdata) => {
return fetchdata.json();
}).then((readingData) => {
console.log(readingData);
}).catch((err) => {
console.log(err);
});
Finally, this seems unlikely, but if you really want to fetch it once and use that one result in multiple places via the promise chain, keep the promise from then rather than the promise from fetch:
let thisIsUrl = 'https://api.covid19api.com/summary';
let a = fetch(thisIsUrl)
.then((data) => {
return data.json()
});
a.then((apidata) => {
// ***** Use it here
}).catch((error) => {
console.log(error)
})
a.then((readingData) => {
// ***** And then again here
}).catch((err) => {
console.log(err);
});
Side note: Your code is falling prey to a footgun in the fetch API; I've written about it in this blog post. fetch only rejects its promise on network errors, not HTTP errors. You have to check for those yourself in the first fulfillment handler, by checking for ok on the response object:
fetch("/your/resource")
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status); // Or better, use an Error subclass
}
return response.json();
})
// ...
fetch returns Promise, generally, promises have something like state inside themself;
pending: initial state, neither fulfilled nor rejected.
fulfilled: meaning that the operation was completed successfully.
rejected: meaning that the operation failed.
(source)
So when we call them and get the value from them with then, catch and etc. then they change the state after that call. So here, when you read the value with a.then(…, the promise changes its state to fulfilled and you are not able to call it again, you need a new and fresh Promise, actually a new instance of the fetch.
I want to recommend you to use Promise.all().
let thisIsUrl = 'https://api.covid19api.com/summary';
let a = fetch(thisIsUrl)
.then((data) => {
return data.json()
}).then((apidata) => {
console.log(apidata)
return apidata
}).catch((error) => {
console.log(error)
})
Promise.all([a,a,a]);
.then(results => {
// Results are here.
});
I have my function handleRes who is exec in await.
But i want exec a function when the await is ended. Like with .then or .catch
How can i do something like this
I import this function
const handleRes = res => {
res
.then(({ data }) => {
console.log('done');
})
.catch((error) => {
console.log('error');
});
};
Read it in this file and exec something when it end
await handleRes(res).then(() => setLoading(false));
handleRes doesn't return the promise chain, so you can't wait on its work to finish from outside of it. The solution is to modify it so that it returns the chain:
const handleRes = res => {
return res
//^^^^^^
.then(({ data }) => {
console.log('done');
})
.catch((error) => {
console.log('error');
});
};
Then you can await it. In the normal case, that would like:
await handleRes(res);
setLoading(false);
...but your version using then also works.
In the normal case, you would also remove that error handler so that errors propagate along the chain and are handled by the functions calling handleRes (or the functions calling them, if they pass the chain along). With the function as shown above (with the catch), the caller has no way to know whether the operation succeeded or failed, because the catch converts the rejection into a fulfillment (with the value undefined).
I am building out an Express API built with the mssql package.
If I don't call sql.close() then I get the following error:
Error: Global connection already exists. Call sql.close() first.
I'd like to keep the endpoints easy to follow and maintain and like the following pattern using a finally promise pattern.
const sql = require("mssql")
const config = require("../config")
sql.connect(config.properties).then(pool => {
return pool.request()
.execute('chain')
.then(response => {
res.send(response['recordsets'][0][0]['response'])
})
.catch(err => res.send(err))
.finally(sql.close())
})
However, this generates the following error:
{
"code": "ENOTOPEN",
"name": "ConnectionError"
}
The following code works, but it seems a bit clumsy to define sql.close multiple times in the same function.
sql.connect(config.properties).then(pool => {
return pool.request()
.execute('chain')
.then(response => {
res.send(response['recordsets'][0][0]['response'])
sql.close()
})
.catch(err => {
res.send(err)
sql.close()
})
})
Is there a way to call sql.close as part of the promise chain after either a response or error is sent with res.send?
.finally accepts function, you passing result of function
sql.connect(config.properties).then(pool => {
return pool.request()
.execute('chain')
.then(response => {
res.send(response['recordsets'][0][0]['response'])
})
.catch(err => res.send(err))
.finally(() => sql.close()) // FIX HERE
})
Can someone please explain why returning an Axios promise allows for further chaining, but returning after applying a then()/catch() method does not?
Example:
const url = 'https://58f58f38c9deb71200ceece2.mockapi.io/Mapss'
function createRequest1() {
const request = axios.get(url)
request
.then(result => console.log('(1) Inside result:', result))
.catch(error => console.error('(1) Inside error:', error))
return request
}
function createRequest2() {
const request = axios.get(url)
return request
.then(result => console.log('(2) Inside result:', result))
.catch(error => console.error('(2) Inside error:', error))
}
createRequest1()
.then(result => console.log('(1) Outside result:', result))
.catch(error => console.error('(1) Outside error:', error))
createRequest2()
.then(result => console.log('(2) Outside result:', result))
.catch(error => console.error('(2) Outside error:', error))
<script src="https://unpkg.com/axios#0.16.1/dist/axios.min.js"></script>
https://jsfiddle.net/nandastone/81zdvodv/1/
I understand that Promise methods should return a value to be chained, but why is there a difference between these two return methods?
Your first example returns the original promise. Your second example returns a different promise, the one created by calling catch.
The critical differences between the two are:
In your second example, you're not passing on the resolution value, so the promise returned by your then is resolved with undefined (the return value of console.log).
In your second example, you're converting rejections into resolutions with undefined (by returning the result of console.log out of catch). A catch handler that doesn't throw or return a promise that's rejected converts a rejection into a resolution.
One of the key things about promise chains is that they transform the result; every call to then or catch creates a new promise, and their handlers can modify what's sent downstream as the result passes through them.
The usual pattern would indeed be to return the result of the chain, but for the functions in the chain to either intentionally transform the result or pass it on. Normally, you wouldn't have a catch handler except at the terminal end of the chain, unless you're using it to correct the error condition (intentionally converting a rejection into a resolution).
If you wanted to just log what passed through while still allowing callers to see it but did want to return the result of the chain for whatever reason, you'd do this:
return request
.then(result => { console.log(result); return result; })
.catch(error => { console.error(error); return Promise.reject(error); });
or using throw:
return request
.then(result => { console.log(result); return result; })
.catch(error => { console.error(error); throw error; });