简体   繁体   English

在 IF 语句中使用异步函数的返回值

[英]Using Return Value from Async Function In IF Statement

New to NodeJS and JavaScript NodeJS 和 JavaScript 的新手

I am using NodeJS to make an API call to return some JSON data within an async function.我正在使用 NodeJS 进行 API 调用以在异步函数中返回一些 JSON 数据。 Presently, the API call is working as intended and I have parsed the data that I am looking for.目前,API 调用正在按预期工作,我已经解析了我正在寻找的数据。 The trouble I am having is using that parsed json data as a condition within an IF statement so I can continue along with the rest of the scripts intended functions.我遇到的问题是使用解析的 json 数据作为 IF 语句中的条件,这样我就可以继续执行其他脚本的预期功能。 To simplify for the mean time I have written it to display a string statement if the JSON data is what I expect it to be:为了同时简化,如果 JSON 数据是我所期望的,我已经编写了它来显示字符串语句:

 const fetch = require("node-fetch"); var accessToken = "Bearer <ACCESS TOKEN>"; var url = '<API ENDPOINT>'; var headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': accessToken }; const getData = async url => { try { const response = await fetch(url, {method: "Get", headers: headers}); const json = await response.json(); console.log(json.status); return json.status } catch (error) { console.log(error); } }; let apiStatus = getData(url); let activated = "ACTIVATED"; let configured = "CONFIGURED"; if (apiStatus.toString() !== activated) { console.log("BLAH"); }

Essentially, if the return value of "json.status" is equal to "ACTIVATED", then I will perform an action.本质上,如果“json.status”的返回值等于“ACTIVATED”,那么我将执行一个动作。 Else, I will perform a different action.否则,我将执行不同的操作。

At present, I am unable to use the output of the "getData()" to be used in an IF condition.目前,我无法在 IF 条件中使用“getData()”的输出。 Any assistance with next steps would be appreciated.对后续步骤的任何帮助将不胜感激。

You need to wait for the promise to be resolved, because right now you'd be evaluating a Promise (pending) object.您需要等待承诺得到解决,因为现在您正在评估一个 Promise(待定)对象。

Your getData() function is fine.你的 getData() 函数很好。

let apiStatus = await getData(url);

I don't think async works on the window scope, you can try this out.我认为 async 在窗口范围内不起作用,您可以尝试一下。 If this doesn't work, then you just need to wait for the promise to be resolved.如果这不起作用,那么您只需要等待承诺得到解决。

getData(url).then(
   status => {
      if (status.toString() === 'activated'){
         ...
      }
});

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

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