Just to be sure I understand how async/await works, I'd like to confirm something. Let me first create a couple of functions:
let resolveAfter2Seconds = () => {
console.log("starting slow promise");
return new Promise(resolve => {
setTimeout(function() {
resolve(20);
console.log("slow promise is done");
}, 2000);
});
};
let resolveAfter1Second = () => {
console.log("starting fast promise");
return new Promise(resolve => {
setTimeout(function() {
resolve(10);
console.log("fast promise is done");
}, 1000);
});
};
Now, take these two blocks of code for example:
let concurrentStart = async () => {
console.log('==CONCURRENT START with await==');
const slow = resolveAfter2Seconds();
const fast = resolveAfter1Second();
console.log(await slow);
console.log(await fast);
}
Now, is it the case that the above is functionally equivalent to this:
let concurrentStart = async () => {
console.log('==CONCURRENT START with await==');
const slow = await resolveAfter2Seconds();
const fast = await resolveAfter1Second();
console.log(slow);
console.log(fast);
}
In other words, I can either put the await keyword right before the function call await resolveAfter25Seconds(), or... I can put the await in the console log that triggers the firing of that function - console.log(await slow);.
Will the result be the same, in the sense that async/await will work in the same way in both cases -- in which case you could accomplish the same thing with either approach?