If you want to access the changed version of myval
(that is, execute your code after the assignment inside the Promise has been done), you need to either follow up with yet another then
, or do anything else that'd put your code in the event queue after the assignment.
var promise1 = new Promise(function(resolve, reject) {
resolve('foo');
});
let myval="a";
promise1.then(function(value) {
myval=value;
console.log(value); // this logs "foo"
});
setTimeout(() => console.log(myval), 0); // logs "foo"
var promise1 = new Promise(function(resolve, reject) {
resolve('foo');
});
let myval="a";
promise1.then(function(value) {
myval=value;
console.log(value); // this logs "foo"
}).then(function() {
console.log(myval) // logs "foo"
});
And an await example, probably the one you're looking for:
- wrap everything into an immediately invoked async function, so we can use
await
inside
- save the
.then
promise into a variable (you can, obviously, omit that variable altogether and await
directly)
await
that promise before your console.log
(async () => {
var promise1 = new Promise(function(resolve, reject) {
resolve('foo');
});
let myval="";
var thenedPromise = promise1.then(function(value) {
myval=value;
console.log(value); // this logs "foo"
});
await thenedPromise; // wait before the promise generated by "then" is resolved
console.log(myval); // logs "foo"
})();