简体   繁体   中英

Could anyone tell me why my setTimeout function within the try block does not work?

I have a problem. Could anyone tell me why my setTimeout function within the try block does not work? It doesn't wait for 10000 milliseconds and simple runs through. As a result, the console shows the error message "cannot read property data of "undefined". The API should return an object, but needs some time to fetch the answer. The console.log(responseInformation) returns also "undefined".

const fetchAnswerFromDialogflow = 
try {
      const res = await axios.post(
        `https://dialogflow.googleapis.com/v2/projects/myteachingbot-arxmxd/agent/intents:batchUpdate`,
        node,
        config
      );

      const waitForResponseAssignment = async () => {
        let nodesSavedToChatbot = await res.response.data;
        return nodesSavedToChatbot;
      };

      const responseInformation = setTimeout(
        await waitForResponseAssignment(),
        10000
      );
      
      console.log(responseInformation);

The problems in your code:

const res = await axios.post(
  `https://dialogflow.googleapis.com/v2/projects/myteachingbot-arxmxd/agent/intents:batchUpdate`,
  node,
  config
);

const waitForResponseAssignment = async () => {
   /*
    axios response doesnt have a property called response,
    so res.response.data is error.
    Also res.data is already a response from the api(res is
    not a promise so you dont have to use await below, 
    even you dont need this `waitForResponseAssignment` function)
   */
  let nodesSavedToChatbot = await res.response.data;
  return nodesSavedToChatbot;
};

// This timeout function is not correct, setTimeout
// accepts the first param as callback(but you passed a value)
// Actually you also dont need this `setTimeout`
const responseInformation = setTimeout(
  await waitForResponseAssignment(),
  10000
);

You can just use the below code:


const res = await axios.post(
  `https://dialogflow.googleapis.com/v2/projects/myteachingbot-arxmxd/agent/intents:batchUpdate`,
  node,
  config
);
return res.data;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM