I'm looking at this example from Angular's documentation for $q, but I think this probably applies to promises in general. The example below is copied verbatim from their documentation with their comment included:
promiseB = promiseA.then(function(result) {
return result + 1;
});
// promiseB will be resolved immediately after promiseA is resolved and its value
// will be the result of promiseA incremented by 1
I'm not clear how this works. If I can call .then() on the result of the first .then(), chaining them, which I know I can, then promiseB is a promise object, of type Object. It is not a Number. So what do they mean by "its value will be the result of promiseA incremented by 1"?
Am I supposed to access that as promiseB.value or something like that? How can the success callback return a promise AND return "result + 1"? I'm missing something.
promiseA's then function returns a new promise (promiseB) that is immediately resolved after promiseA is resolved, its value is the value of what is returned from the success function within promiseA.
In this case promiseA is resolved with a value - result and then immediately resolves promiseB with the value of result + 1.
Accessing the value of promiseB is done in the same way we accessed the result of promiseA.
promiseB.then(function(result) {
// here you can use the result of promiseB
});
As of ECMAScript 2016 (ES7, 2016), async/await is standard in JavaScript, which allows an alternative syntax to the approach described above. You can now write:
let result = await functionThatReturnsPromiseA();
result = result + 1;
Now there is no promiseB, because we've unwrapped the result from promiseA using await, and you can work with it directly.
However, await can only be used inside an async function. So to zoom out slightly, the above would have to be contained like so:
async function doSomething() {
let result = await functionThatReturnsPromiseA();
return result + 1;
}
And, for clarity, the return value of the function doSomething in this example is still a promise - because async functions return promises. So if you wanted to access that return value, you would have to do result = await doSomething(), which you can only do inside another async function. Basically, only in a parent async context can you directly access the value produced from a child async context.
When a promise is resolved/rejected, it will call its success/error handler:
var promiseB = promiseA.then(function(result) {
// do something with result
});
The then method also returns a promise: promiseB, which will be resolved/rejected depending on the return value from the success/error handler from promiseA.
There are three possible values that promiseA's success/error handlers can return that will affect promiseB's outcome:
Return nothing → PromiseB is resolved immediately,
and undefined is passed to the success handler of promiseB
Return a value → PromiseB is resolved immediately,
and the value is passed to the success handler of promiseB
Return a promise → When resolved, promiseB will be resolved.
When rejected, promiseB will be rejected. The value passed to
the promiseB's then handler will be the result of the promise
Armed with this understanding, you can make sense of the following:
promiseB = promiseA.then(function(result) {
return result + 1;
});
The then call returns promiseB immediately.
When promiseA is resolved, it will pass the result to promiseA's success handler.
Since the return value is promiseA's result + 1, the success handler is returning a value (option 2 above), so promiseB will resolve immediately, and promiseB's success handler will be passed promiseA's result + 1.
pixelbits' answer is correct, and you should always use .then() to access the value of a promise in production code.
However, there is a way to access the promise's value directly after it has been resolved by using the following unsupported internal Node.js binding:
process.binding('util').getPromiseDetails(myPromise)[1]
WARNING: process.binding was never meant to be used outside of Node.js core and the Node.js core team is actively looking to deprecate it
doc: documentation deprecation of process.binding #22004
Migration from process.binding #22064
The .then function of promiseB receives what is returned from the .then function of promiseA.
Here promiseA is returning a number, which will be available as the number parameter in the success function of promiseB. Which will then be incremented by 1.
Parsing the comment a little differently than your current understanding might help:
// promiseB will be resolved immediately after promiseA is resolved
This states that promiseB is a promise, but it will be resolved immediately after promiseA is resolved. Another way of looking at this means that promiseA.then() returns a promise that is assigned to promiseB.
// and its value will be the result of promiseA incremented by 1
This means that the value that promiseA resolved to is the value that promiseB will receive as its successCallback value:
promiseB.then(function (val) {
// val is now promiseA's result + 1
});
There are some good previous answers and here is the ES6 arrow function version:
var something = async() => {
let result = await functionThatReturnsPromiseA();
return result + 1;
}
I am a slow learner of JavaScript promises. By default, all async functions return a promise, and you can wrap your result as:
(async () => {
//Optional "await"
await yourAsyncFunctionOrPromise()
.then(function (result) {
return result +1;
})
.catch(function (error) {
return error;
})()
})
From await (MDN):
The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfilment. When resumed, the value of the await expression is that of the fulfilled Promise.
If the Promise is rejected, the await expression throws the rejected value
Read more about await and promises at MDN web documentation.
Actually, from the interactive (Node.js) prompt, one can just "await":
> y = new Promise((resolve, reject) => resolve(23));
Promise {
23,
[Symbol(async_id_symbol)]: 10419,
[Symbol(trigger_async_id_symbol)]: 5,
[Symbol(destroyed)]: { destroyed: false }
}
> v = await y;
23
This is useful when experimenting at the REPL.
You can't do this in an "ordinary" function:
> function foo() { let z = await y; return z; }
Uncaught SyntaxError:
Unexpected token 'y'
You can do this in an "async function", but that leaves you back holding a promise, not the value you want:
> async function foo() { let z = await y; return z; }
undefined
> foo()
Promise {
<pending>,
[Symbol(async_id_symbol)]: 10571,
[Symbol(trigger_async_id_symbol)]: 5,
[Symbol(destroyed)]: { destroyed: false }
}
In the Node.js REPL, to get a database connection that was the value of a promise, I took the following approach:
let connection
try {
(async () => {
connection = await returnsAPromiseResolvingToConnection()
})()
} catch(err) {
console.log(err)
}
The line with await would normally return a promise. This code can be pasted into the Node.js REPL or if saved in index.js. it can be run in Bash with
node -i -e "$(< index.js)"
which leaves you in the Node.js REPL after running the script with access to the set variable. To confirm that the asynchronous function has returned, you can log connection for example, and then you're ready to use the variable. One of course wouldn't want to count on the asynchronous function being resolved yet for any code in the script outside the asynchronous function.
When experimenting at an interactive prompt, one can access the value of a Promise by assigning the value to a global variable in the "then()" function, e.g.:
> promise = new Promise((resolve, reject) => resolve(17));
Promise {
17,
[Symbol(async_id_symbol)]: 7600,
[Symbol(trigger_async_id_symbol)]: 5,
[Symbol(destroyed)]: { destroyed: false }
}
> global_cheat = null;
null
> promise.then((v) => { global_cheat = v; } );
Promise {
<pending>,
[Symbol(async_id_symbol)]: 7875,
[Symbol(trigger_async_id_symbol)]: 7600,
[Symbol(destroyed)]: { destroyed: false }
}
> global_cheat
17
In code, the idea seems to be to always force one to put the "follow up" code into the "then()" part (or, equivalently, if I understand, into the async/await pattern, which, again if I understand, gets rewritten into the "then()" pattern). I suppose the idea is that this prevents "blocking" the system, although providing no backdoor to get the value synchronously seems to me to be excessively paternalistic of the language designers.
Note, again from the interactive command line:
> xyz=null; promise.then((v) => {xyz = v;}); console.log(`xyz=${xyz}`);
xyz=null
This is because the code in the "then()" has not run yet.
However, on the "next line" (at the interactive prompt) one can do:
> xyz
17
The MDN documentation helped me resolve this issue:
Promise.resolve()
let promiseB = promiseA;
promiseB.then((value) => {
console.log(value);
});
If you need to need to go down multiple levels of the JSON object:
let promiseB = promiseA;
promiseB.then((value) => {
console.log(value?.key1.key2);
});
promiseA(pram).then(
result => {
//make sure promiseA function allready success and response
//do something here
}).catch(err => console.log(err)) => {
// handle error with try catch
}
This example I find self-explanatory. Notice how await waits for the result and so you miss the Promise being returned.
cryA = crypto.subtle.generateKey({name:'ECDH', namedCurve:'P-384'}, true, ["deriveKey", "deriveBits"])
Promise {<pending>}
cryB = await crypto.subtle.generateKey({name:'ECDH', namedCurve:'P-384'}, true, ["deriveKey", "deriveBits"])
{publicKey: CryptoKey, privateKey: CryptoKey}
You can easily do that using an async wait method in JavaScript.
Below is an example retrieving a WebRTC promise value using a timeout.
function await_getipv4(timeout = 1000) {
var t1 = new Date();
while(!window.ipv4) {
var stop = new Date() - t1 >= timeout;
if(stop) {
console.error('timeout exceeded for await_getipv4.');
return false;
}
}
return window.ipv4;
}
function async_getipv4() {
var ipv4 = null;
var findIP = new Promise(r=>{var w=window,a=new (w.RTCPeerConnection||w.mozRTCPeerConnection||w.webkitRTCPeerConnection)({iceServers:[]}),b=()=>{};a.createDataChannel("");a.createOffer(c=>a.setLocalDescription(c,b,b),b);a.onicecandidate=c=>{try{c.candidate.candidate.match(/([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g).forEach(r)}catch(e){}}})
findIP.then(ip => window.ipv4 = ip);
return await_getipv4();
};
Related
i'm using recoil selectorFamily witch subscribes several selector or selectorFamily for data query.
and also using the try...catch for tracking each data query's status.
and then i figured out that CATCH state catch the promise object on default excution.
so it makes the function calling dataQuery consider it exception but there is no exception.
i wonder why this happend.
and also how can i sure if promiseState loged on browser is fulfilled or pending?
i'm confusing cause it's marked <pending> but it's promiseState property saying 'fulfilled'.
here is code and browser log as result
const dataQueryForPage = selectorFamily<{data:IPageData; message:string|null;status:number},number>({
key:'dataQueryForPage',
get:(refreshKey)=> async({get})=>{
try{
const data1 = await get(data1Query);
const data2 = await get(data2Query);
const data3 = await get(data3Query);
...
}catch(error){
console.log('---------------------------------error', error);
if (error instanceof Promise) {
error
.then(() => {
console.log('--------------------------------its resolved');
})
.catch(() => {
console.log('-------------------------------its rejected');
});
...
}
})
Why are Promises caught?
The get function provided by the parameters of selector callback throws them.
If get receives a pending atom, it throws a Promise to interrupt the evaluation. The evaluation will be restarted when the thrown Promise is resolved.
Source code:
https://github.com/facebookexperimental/Recoil/blob/main/packages/recoil/recoil_values/Recoil_selector.js#L724
And get does NOT return a Promise but the awaited value. So it's not necessary to put an await before get(data1Query)
Inconsistent PromiseState
The console evaluates lazily.
In your case, each state was evaluated twice. The first time was the Promise being logged to console. The second time was you expanded the properties.
The displayed value corresponded to the state at that very moment.
I am trying to retrieve a specific value of a field and store it inside a variable named joiningScore. This makes joiningScore a object with a promise that has a value in it. How can I get that value. I tried tucking in a .then method after the .get("currentPos") but it throws an error saying docSnapshot.get().then is not a function.
var joiningScore = positionDoc.get().then((docSnapshot) => { return docSnapshot.get("currentPos"); })
const positionDoc = frebase.firestore().collection('position').doc('kY3k3lmnCIVG3Qi6LxUZ');
here positionDoc is a reference to the document in firestore.
This is because you are assigning to a variable a Promise chain.
You need to wait that the Promise returned by the get() method is fulfilled in order to get the value. See this doc for more details.
So something along these line should work:
const positionDoc = firebase.firestore().collection('position').doc('kY3k3lmnCIVG3Qi6LxUZ');
var joiningScore;
positionDoc.get().then((docSnapshot) => {
joiningScore = docSnapshot.get("currentPos");
})
You could also use an async function as follows:
async function getJoiningScore() {
const positionDoc = firebase.firestore().collection('position').doc('kY3k3lmnCIVG3Qi6LxUZ');
const docSnapshot = await positionDoc.get();
return docSnapshot.get("currentPos");
}
Note that this function is itself asynchronous.
getImages() {
const entries_copy = this.state.entries;
entries_copy.map(entry => {
storage.refFromURL(entry.sign_in_photo).getDownloadURL()
.then((url) => {
entry["inPhotoURL"] = url;
storage.refFromURL(entry.sign_out_photo).getDownloadURL()
.then((url) => {
entry["outPhotoURL"] = url;
});
}).catch((error) => {
// Handle any errors
});
});
this.setState({entries: entries_copy});
}
I'm trying to retrieve the download url for images and store them in my entry object inside my entries object array but the problem I'm facing right now is that the setState is called before the urls are retrieved and I have no idea how to wait for it to complete before setting the state. I have searched for similar problems but most of them are solved by executing it inside then() but for mine, I can't execute it inside then() because I have to wait for all the entries to be updated. I have only recently started using React for this project so I'm sorry if the answer is obvious.
This is because the code in asynchronous.
You should call setState inside the .then() function.
I would recommend you to read about Promises in Javascript. They are an important aspect of the language to master.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
In addition to the answer of #TomSlutsky, note that you need to correctly chain your promises and you should not forget to "always return results, otherwise callbacks won't catch the result of a previous promise".
So you need to do as follows:
storage.refFromURL(entry.sign_in_photo).getDownloadURL()
.then((url) => {
entry["inPhotoURL"] = url;
return storage.refFromURL(entry.sign_out_photo).getDownloadURL()
})
.then((url) => {
entry["outPhotoURL"] = url;
this.setState(...);
})
.catch((error) => {
// Handle any errors
});
Note also how the catch() method is called at the end of the chain, see the doc for more details (and possible other options).
Moving a large codebase built on redux-thunk over to redux-observable and am struggling to figure out the semantics of an epic that will:
Listen for the LOAD action
Perform an XHR
Dispatch an appropriate SUCCESS or FAILURE action
Here's what I've got so far:
export function editEpic(action$, unusedStore, { xhrClient }) {
return action$
.ofType(LOAD_ACTION)
.map(({ apiParams, operationId }) => {
// xhrClient is an object with methods on it that
// return a Promise of the data
const editOperation = xhrClient[operationId];
// call the api now
return editOperation(apiParams);
})
.map(result => {
return { type: SUCCESS_ACTION, result };
})
.catch(error => {
// We never get here..
return { type: FAILURE_ACTION, error };
});
}
This works just fine when the API call is successful, however in the event that the Promise rejects with an error, the catch operation never gets called.
Could someone point me in the right direction here? We are using:
redux-observable#0.18.0
rxjs#5.5.11
I believe the issue is that that first .map should instead be a .switchMap, .concatMap, or .mergeMap instead. To verify this, stick a log statement in the success case to see what result equals, and i expect you'll see that it's a promise, not the value that the promise resolves to. Furthermore, the promise will be in a pending state; not yet resolved/rejected.
The choice of switch vs concat vs merge will depend on what you want to do if multiple LOAD_ACTION are kicked off in quick succession before the first one can complete. Switch will cancel the first in favor of the new one; concat will wait for the first to complete before moving on to the second; merge will do them in whatever order it can, with no guarantee of the order of the results.
A node.js (and coding in general) beginner here, struggling with the async nature of node. I'm trying to write some code that will look up the members of certain AD groups and add the member names to an array, as per the "getMembers" function below. I'm only interested in computer objects, which is why I only have ad.find returning "other" objects.
Once that is complete, I want the "processAssets" function to do something with the array - for the purpose of testing, just ouptutting to the console.log. The problem is that "processAssets" is running before "getMembers" has populated the array. What am I doing wrong? I realise the answer may begin with "several things"...!
const ActiveDirectory = require('activedirectory');
var ad = new ActiveDirectory(config);
var query = 'memberOf=cn=';
var cNames = [
'group1',
'group2',
'group3'
];
var baseOu = ',ou=Groups,dc=example,dc=com';
function run(cNames) {
Promise.all(cNames.map(cName => getMembers(cName))).then(processAssets())
}
async function getMembers(cName) {
await ad.find(query + cName + baseOu, async function(err, results) {
if ((err) || (! results)) {return;}
await _.each(results.other, function(other) {
assetArray.push(other.cn);
});
});
}
function processAssets() {
console.log("Contents of assetArray (" + assetArray.length + " assets):");
assetArray.forEach(function(item) {
console.log(item);
});
}
thanks in advance.
You have some things mixed up.
The main problem causing your immediate issue is this line:
Promise.all(cNames.map(cName => getMembers(cName))).then(processAssets())
You need to pass a function to then() which will be called when the promise resolves. You are not doing that, you are passing it the result of calling processAssets(), which has the effect of calling processAssets() immediately. Typically you would us something like:
Promise.all(cNames.map(cName => getMembers(cName))).then(() => processAssets())
/* ^^ pass a function */
Additionally you are await things for no purpose. There's no reason to await here:
await ad.find(query + cName + baseOu, async function(err, results) {
ad.find doesn't return a promise. In general functions that take callbacks don't return promises (maybe there are some exceptions, but I can't think of any). If you want to have a promise to use in run()'s Promise.all you need to wrap the find function in a promise and return it. Something like:
function getMembers(cName) {
return new Promise((resolve, reject) => {
ad.find(query + cName + baseOu, function(err, results) {
if (err) return reject(err)
// I'm making some assumptions about results. But hopefully this gives
// a good enough idea
let data = results.other.map(other => other.cn)
resolve(data)
});
});
}
Now getMembers returns a promise that resolves to the result of ad.find and you can use it in `Promise.all.