All current responses are of course correct but please keep in mind some differences.
Currently in both your solutions promises are invoked in parallel. This might lead to some errors.
Consider such case (slight modifications to your case 1):
var response1 = await rp('https://api.example.com/endpoint1');
var response2 = await rp('https://api.example.com/endpoint2');
return response1 + ' ' + response2;
In above case promise2 will be executed AFTER promise1 finishes executing itself. The result is already known when promise2 is started. Your cases, on the other hand, run them all together in some kind of a race. Therefore if in second call to rp would contain logic that depends on some action that is done in first call to rp, it might lead to unexpected results or even to crash. Good example would be writing and reading to the same file.
Let's consider following example:
function writeToFile()
{
return new Promise((resolve, reject) => {
... // writing to file abc.txt
};
}
function readFile()
{
return new Promise((resolve, reject) => {
... // reading file abc.txt
};
}
function raceCondition()
{
Promise.all([
writeToFile(),
readFile()
]);
}
async function asyncAwait()
{
await writeToFile();
await readFile();
}
raceCondition() function might lead to unexpected behavior because readFile might be run while writeToFile function did not even finish writing to the file. It could lead to reading some old data, or even file might not even exist.
asyncAwait() function uses async/await approach that guarantees that writeToFile() function finishes its work before reading starts. Of course it does not mean that the program becomes synchronous. In the meantime other operations are performed (i.e. some GUI events processing etc).
Async/Await should be then considered as an alternative to .then().then() chain rather than to Promise.all
async/awaitis forPromisesnot vsPromisesawaited. They will execute in parallel in both cases.var r1 = await rp('https://api.example.com/endpoint1'); var r2 = await rp('https://api.example.com/endpoint2')The behaviour would be different: requests would run sequentually.