简体   繁体   中英

How do I wait for a value to be retrieved from API calls. Before starting my code

Supposed I have a json object from a url.

fetch(URL, setting)
.then(loadRes)
.then(logger)


function loadRes (res){
  return res.json();
}

Not sure whether async is needed right below.

async function logger (reply){
  let stringReply = await reply.answer;
  console.log("Obtain value " + stringReply) //let the value be a string e.g "apple"

  sendingReply(stringReply);

  return stringReply
}

Using express

app.post('/', function( req, res){

    console.log(sendingReply()) 
}

when i tried logging the results again, it shows promise { <pending> } So how can I retrieved the value from the earlier on. Waiting for the value to be retrieved

Correct me if I'm wrong, my understanding is that when the code is being run, it execute everything at once. So therefore by the time I received a result from the URL link (json object) , it is already done executing it.

If you are sure that reply.answer is a resolved promise, then only await would be required. Since you've mentioned it is returning Promise { <pending> } , I guess it would be an unresolved Promise which gives a pending state.

x=new Promise((resolve,reject)=>("vre")) //gives Promise {<pending>}

x=new Promise((resolve,reject)=>resolve("vre")) //gives Promise {<resolved>: "vre"}

I hope that resolves your concern.

  1. If you're using await then async function is required and in this case correctly used. However, await has to be used before a promise call.

What does reply.answer return? if it returns a promise then reply.answer() is the correct way to call that function.

  1. Please let know your output error message, also let me know what's the purpose on sendingReply() , it's supposed to return a promise? does it return a value?

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