Home > front end >  Trying to execute an imported Async function but the function is not behaving asynchronously
Trying to execute an imported Async function but the function is not behaving asynchronously

Time:10-02

I am using React to build a website. I have imported an asynchronous function to execute when I press a button. However, the function is not working asynchronously and I really don't understand why.

interact.js:

export const getNFT = async () => {
  setTimeout(() => {
    console.log('getNFT code execute');
    return nft;
  }, 2000);
};

const nft = {
tokenURI: 'https://gateway.pinata.cloud/ipfs/QmdxQFWzBJmtSvrJXp75UNUaoVMDH49g43WsL1YEyb',
imageURL: 'https://gateway.pinata.cloud/ipfs/QmeMTHnqdfpUcRVJBRJ4GQ2XHU2ruVrdJqZhLz',
ID: '212'
};

Main.js

import {
  getNFT
} from 'interact.js';


// This function is executed when a user clicks on a button
let getAllocatedNFT = async () => {
try {
  let response = await getNFT();
  console.log('response from server:: ' response);
}catch(e){
  console.log(e);
}
};

console:

response from server:: undefined
getNFT code execute // This is executed correctly after 2 seconds

CodePudding user response:

You have to return promise which will resolve your webAPI(setTimeout) Please use like below:

  const getNFT = async () => {
    return new Promise(resolve => setTimeout(() => {
        console.log("getNFT code execute")
        resolve(true)
      }, 2000)
    );
  };
  • Related