I was following an async/await tutorial. Even though I'm copying the code 1:1, it doesn't work as intended.
Here's a function, it accepts a fruit name as a parameter and returns a number accordingly. It's asynchronous, so it should return a promise.
const getFruit = async(name) => {
const fruits = {
pineapple: 1,
apple: 2,
strawberry: 3
}
return fruits[name]
}
Works as intended, doing getFruit("apple").then(result => console.log(result))
returns 2.
Afterwards, I have the second function that runs the getFruit
function twice to get two numbers, awaits the results and then combines them. In theory.
const makeSmoothie = async() => {
const a = await getFruit("apple")
const b = await getFruit("strawberry")
const smoothie = [a, b]
return smoothie
}
But in reality, console.log(makeSmoothie())
then returns a Promise { <pending> }
. Why?
Also, I'm aware that I'm actually unnecessarily preventing the script from getting the value b
until a
is retrieved. It just looks simpler this way. Assigning both values and then doing const smoothie = await Promise.all([a, b])
doesn't work, either. Same results.