简体   繁体   中英

Promise is returning <pending>

I've written a little code snipped for a http request. After I realized request is async, I rewrote my code with a promise. But it's telling me that the promise is pending. I have absolute no idea why it is wrong. Here my code:

function verifyUser(uname,pword){
    var options = {
        url: 'CENSORED',
        method: 'POST',
        headers: headers,
        form: {'Username':uname, 'Password':pword, 'Key':key},
        json:true
    }
    return new Promise((r,j) => request(options,(error,response,body)=>{
        if(error){
            console.log("[ERROR] Promise returned error");
            throw j(error);
        }
        r(body);
    }))
} 
async function receiveWBBData(uspass,passwd){
    const data = await verifyUser(uspass,passwd);
    return data;
}

var test1 = receiveWBBData("r0b","CENSORED");
console.log(test1);`

Thanks in advance!

receiveWBBData is async. Therefore, test1 is a promise. If you want to log the result, do test1.then(console.log).catch(console.error) , or use var test1 = await receiveWBBData(/*...*/) if you want the result in your variable. Note that await can only be used in async functions.

Also, as @somethinghere mentionned, you should not throw your promise rejection, you should return it.

An async function always returns a promise . In order to "unwrap" a promise, you need to await on it, so you need var test1 = await receiveWBBData("r0b","CENSORED"); .

Top-level await is not part of the language yet, so I'd recommend you add a function called main() or run() and just call that when your script starts.

async function receiveWBBData(uspass,passwd){
  const data = await verifyUser(uspass,passwd);
  return data;
}

async function main() {
  var test1 = receiveWBBData("r0b","CENSORED");
  console.log(test1);`
}

main().catch(error => console.error(error.stack));

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