简体   繁体   English

执行 api 并等待 javascript 中的响应代码执行

[英]execute an api and wait for the response code execution in javascript

I need to wait for a api response to return before the subsequent result to be executed.在执行后续结果之前,我需要等待 api 响应返回。 So I tried with promise calls in js.所以我尝试在 js 中调用 promise 。 But still it doesn't wait for the api response.但它仍然没有等待 api 响应。 My attempt is as below.我的尝试如下。

 getAgentList(data); //here data object receiving data
 console.log("executed before the api response");
  var getAgentList = function (dataFromMsg) {
  const myPromise = new Promise(function (resolve, reject) {
    
    let accountNum = window.localStorage.account;
    fetch("/web/main?account=" + accountNum, {
      method: "GET",
    })
      .then(function (res) {
        return res.json();
      })
      .then(function (data) {
        let friendArrList = data.data.friend[0].list;
        
        for (let i = 0; i < friendArrList.length; i++) {
          if (friendArrList[i].id == dataFromMsg.id) {
            dataFromMsg.avatar = friendArrList[i].avatar;
            dataFromMsg.username = friendArrList[i].username;
            break;
          }
        }
        dataFromMsgG = JSON.parse(JSON.stringify(dataFromMsg)); //dataFromMsgG is global object
     
        resolve("fine");
      })
      .catch((error) => {
        console.error("Error:", error);
        reject("error");
      });

   
  });

  myPromise
    .then(function whenOk(response) {
      console.log("response", response);
      return response;
    })
    .catch(function notOk(err) {
      console.error(err);
    });
  };
}

But it will print "executed before the api response" line without waiting for api response.但它会打印“在 api 响应之前执行”行,而无需等待 api 响应。 So where I was get wrong and how could be wait until the api response get success?那么我在哪里弄错了,怎么能等到 api 响应成功?

I suggest to use await and async with promise.我建议将awaitasync与 promise 一起使用。 Since the await is only valid in async function then I have to put your code in a async function which I named it as main .由于await 仅在 async function 中有效,因此我必须将您的代码放入async function 中,我将其命名为main

<script>
    main();

    async function main() {
        
        await getAgentList();
        console.log("executed before the api response");
        
        function getAgentList() {
            const myPromise = new Promise(function (resolve, reject) {
                ///...
                ///... Your code
                ///...
            });

            myPromise
              .then(function whenOk(response) {
                  console.log("response", response);
                  return response;
              })
              .catch(function notOk(err) {
                  console.error(err);
              });
           
            return myPromise;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 代码执行是否等待Ajax响应? - Does code execution wait for Ajax response? 在 useEffect 中执行代码之前等待 axios 响应 - Wait for axios response before execute code in useEffect Javascript在代码执行之前等待ajax成功 - Javascript wait for ajax success before code execution 等待长执行响应 - Wait for a long execution response Javascript(Chrome 扩展):如何正确执行多个 API 调用,使用 fetch 和强制代码等待调用完成? - Javascript (Chrome Extension): How to correctly execute multiple API calls using fetch and force code to wait for the calls to finish? 如何在继续执行之前等待单独的 function 中的 API 响应? - How to wait for API response in separate function before continuing execution? 如何让JavaScript执行等待socket.on函数响应? - How to make JavaScript execution wait for socket.on function response? 如何等待流星调用响应,然后在javascript中执行其他语句? - How to wait for meteor call response and then execute other statements in javascript? 等待内部函数等待并执行然后继续执行 - Wait for inner functions to wait and execute then proceed execution 等待在javascript中执行 - Wait for execution in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM