当前位置: 代码迷 >> JavaScript >> NativeScript http.getJSON和异步等待
  详细解决方案

NativeScript http.getJSON和异步等待

热度:105   发布时间:2023-06-05 15:57:07.0

我在NativeScript应用程序中处理承诺后的退货问题。 返回在http.getJSON获取数据之前执行。 它只是跳过返回不变的(状态)变量。 我试图使用await,但是那没有用或者我没有正确使用它。 这是我的代码

const check = {  
CheckLenght: function(id) { 
    var status = false; 
    var response = checkPoints(id); 

    if(response > 10){
        status true;
    } else {
        status false;
    } 

    console.log("This is response: " + status); // this shows up before getJSON is returned as "This is response: false"

    return status;  // always returns false
 }  
} 


function checkPoints(id){
    let points; 
    http.getJSON('MY_API_URL' + id)
   .then(function (response) {  
        points = response[0].point; 
   }, function(error) {
       console.log("Server err."); 
   }) 

 console.log("This output shows up before - This is response: false ");
 return points;  
} 

有没有办法让这个工作? 我尝试使用Observable,但以太无法正常工作。

更新:

这是我从中调用CheckLenght: function(id)使用var resp = ProvjeraBarcode.CheckLenght(result.text); CheckLenght: function(id) var resp = ProvjeraBarcode.CheckLenght(result.text); 然后返回[object Promise]

function skeniraj(){ 
barcodescanner.scan({
    formats: "QR_CODE, EAN_13",    
    cancelLabel: "Odustani. Probajte Volume tipke",  
    closeCallback: function () { console.log("Scanner closed"); },  
    openSettingsIfPermissionWasPreviouslyDenied: true  
  }).then(
      function(result) {
        console.log("Scan format: " + result.format);
        console.log("Scan text:   " + result.text);  

//#########################            

      var resp = ProvjeraBarcode.CheckLenght(result.text);

//########################## 

       console.log("Show response: "+JSON.stringify(resp)); 
       // output is: "[object Promise]"


        if(resp === "true"){ 
            // if true... 
                setTimeout(func, 50);
                function func() {
                    dialogs.confirm({
                        title: "Kartica je valjana",
                        message: "Pohranite karticu u memoriju?",
                        okButtonText: "Pohrani",
                        cancelButtonText: "Odustani", 
                    }).then(function (response) { 
                        console.log("Dialog result: " + response);
                        if(response){  
                        // save details to storage...

                        } 
                    });
                } 

            } else {
                // .... do something else...
            } 
      },
      function(error) {
        console.log("Nista nije skenirano Err. " + error);
        // pokreni rucni unos
        setTimeout(rucniUnos, 50); 
      }
  ); 
 }

我很难过 感谢您的所有帮助和支持

以这种方式查看您的代码:

function checkPoints(id){

  let points;
  // make a new variable, nothing is assigned so give it undefined

  http.getJSON('MY_API_URL' + id).then(...)
  // Promise? handle later, go to next line.

  return points;
  // return undefined
} 

点将始终是undefined 您可以在http.getJSONthen内部分配point ,因此实际上即使该函数是同步的,外部范围的point仍将是undefined 编辑如果函数是同步的并且不会修改point then您就不会使用, then太糟糕了!

您可以更改代码,以便checkPoints()返回Promise,以确保您已返回数据。

function checkPoints(id){
  return http.getJSON('MY_API_URL' + id).then(
    function (response) {  
      return response[0].point;  <-- return the response[0].point
    },
    function(error) {
      console.log("Server err."); 
    })
}

或带有箭头功能

const checkPoints = (id) => http.getJSON(`MY_API_URL${id}`)
  .then(response => response[0].point)
  .catch(error => console.log("Server err."))

在您的函数中,您可以使用async / await:

...
//             V checkLengtht has to be an async function, otherwise it can't use await
CheckLenght: async function(id) { 
  var status = false;
  var response = await checkPoints(id);
      if(response > 10){
        status true;
    } else {
        status false;
    }
  return status;
}

您可以这样重写代码:

CheckLenght: async function(id) { 
  const points = await checkPoints(id);
  return (points > 10) // return true if points > 10, else return false. Note that this function's return will be wrapped in Promise.
}

注意,CheckLength现在是一个异步函数,这意味着它返回Promise。 使用它时,必须使用await.then()

您也可以完全取消异步/等待:

...
CheckLenght: id => checkPoints(id).then(points => points > 10);

如何使用异步/等待

在函数声明前附加async会使其返回Promise。

const add = (a, b) => a + b
add(1, 2) // 3

const add = async (a, b) => a + b
add(1, 2) // Promise(...)
add(1, 2).then(res => console.log(res)) // 3

可以在async函数中使用await来检索Promise的响应。

const main = async () => {
  const res = await add(1, 2)
  console.log(res)
}

main() // 3
  相关解决方案