How do i synchronously get the result of a Promise [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
Hello I have a function that goes to the database and returns array of objects like so:
function findAlbumImages(){
remote.findAlbum.then(
res =>{
})
}
but I want to call this from another function and assign that res to array collection like so:
let newArray = findAlbumImages();
Is there a way to do this?

Sure you can, by using async/await, which is the closest you can
get to your desired syntax:
function findAlbumImages() {
return remote.findAlbum()
}
(async () => {
let newArray = await findAlbumImages()
console.log(newArray)
})()

Related

How to assign a fetch response to global variable? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 months ago.
const loadUsers = async () => {
const res = await fetch('https://www.breakingbadapi.com/api/characters')
const json = await res.json()
return json
}
let chars = loadUsers()
Why does it return a promise ? If i try to add await keyword to load users i get an error? So what s the problem here?
Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Issue in using async/await function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Use Async/Await with Axios in React.js
(3 answers)
Closed 1 year ago.
I am new to this whole async function concept. Here is the function that I want to use:
async function fetchData() {
try {
const resultRes = await fetch("https://www.breakingbadapi.com/api/characters?category=Better+Call+Saul");
const result = await resultRes.json();
return result;
} catch (error) {
console.error(error);
}
}
And this is what function call looks like:
const Data = fetchData();
Now I want to console.log(Data) with the array that is returned but intead it shows as a promise object.
How should I use this function as using it with .then messes up my whole app as the containing file is a react component?

Prevent function from giving an object promise [duplicate]

This question already has answers here:
Async function returning promise, instead of value
(3 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
The following code logs [Object Promise] instead of a string which is a thing I don't want.
I've tried to make them both async function yet that didn't work.
...
let URL = searchYouTube(arg)
console.log(URL)
...
searchYouTube function:
async function searchYouTube(args) {
youtubes(args, function (err, r) {
let video = r.videos
let Fvideo = video[0]
console.log(Fvideo.url)
return String(Fvideo.url)
})
}

Array undefined from Fetch API [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I can access the array 'words' in global scope but when I try to find an item by typing 'words[index]' , it returns undefined. How can I solve this?
let words = [];
function fetchWords() {
fetch("https://www.themealdb.com/api/json/v1/1/categories.php")
.then((res) => res.json())
.then((data) => {
for (let i = 0; i < 13; i++) {
words.push(data.categories[i].strCategory);
}
});
}
fetchWords();`
console.log(words); //This works
console.log(words[2]); // But this does not. Why?
This is because you call:
console.log(words[2]);
before you fetch the result. You need to await fetchWords before console.log(words[2]);

How to push a promise's return value into an array? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm new to JavaScript so sorry if the question is too dumb.
I have an async function getPartners() in file1.js wich returns an array like this:
return Promise.resolve(partners);
['1','2','3']
In file2.js I have an array with partnerIds and an emptyArray. My goal is when I call getPartners() in file2.js, emptyArray becomes equivalent to the function's return value. In other words I'd like to push the returned values to the emptyArray.
Currently I can get the values this way:
let emptyArray = listItems();
emptyArray.then((result) => {
console.log(result);
});
My problem is that if I try to console.log(emptyArray) outside of the .then, it's empty. I'd like to filter it too, after getting the values from the promise so I need to save the values into an array which I can call later in the code.
How can I do that?
EDIT:
This is what I want to achieve:
const { getPromiseResult } = require('./list');
let existingIds = ['1','2','3'];
let emptyArray = getPromiseResult();
emptyArray.then((resultArrayfromPromise) => {
console.log(resultArrayfromPromise) // ['2','3','4']
// filter the results by the existingIds array's elements
// get result: ['1','2','3','4']
// and get this result in a new filtered array which I can reach from the outside
});
filteredArray.dosomeotherstuff();
Since ES7, you can use async/await to get rid of then. await waits for operation to complete, and if there is a return value assigns it to the variable.
But you can only use the await in an async function so wrap your codes in it.
async function run() {
const { listItems } = require('./list');
let existingIds = ['1','2','3'];
let emptyArray = await getPromiseresult();
console.log(emptyArray); // now it's not empty
filteredArray.dosomeotherstuff();
}
run();

Categories

Resources