NativeScript http.getJSON和异步等待

时间:2019-03-03 00:03:42

标签: javascript api request nativescript

我在NativeScript应用程序中处理诺言后的退货问题。在 http.getJSON 获取数据之前,返回get执行。它只是跳过返回不变的(状态)变量。我曾尝试使用 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);的代码,它返回[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); 
      }
  ); 
 }

我在这方面遇到困难。感谢所有帮助和支持

1 个答案:

答案 0 :(得分:3)

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

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您在point的{​​{1}}内分配了http.getJSON,因此实际上即使该功能是同步的,外部范围的then仍然是{{1} }。 编辑如果该函数是同步的,则您将不会使用point,而对undefined的功能将会被修改,这很糟糕!

您可以更改代码,以使then返回Promise,以确保您已返回数据。

point

或带有箭头功能

checkPoints()

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

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."))

请注意,CheckLength现在是一个异步函数,这意味着它返回Promise;使用时,必须使用... // 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. }

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

await

如何使用异步/等待

在函数声明前附加.then()使其返回Promise。

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

async可以在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 函数中使用,以检索Promise的响应。

await