简体   繁体   English

异步/等待不等待诺言完成

[英]Async/Await not waiting for promise to finish

I have this post route: 我有这样的帖子路线:

  app.post("/new", async (req, res) => {
    const Lob = require("lob")({ apiKey: keys.LOB_API });

    let toAddress = await lobFuncs.toAddress(req.body.addrLine1, Lob);

    console.log("test");
  });

The toAddress() function looks like this: toAddress()函数如下所示:

toAddress: async (address, Lob) => {
    await this.parseGoogleCiv(address, obj => {
      console.log(obj);
    });
  },

parseGoogleCiv: async (address, callback) => {
    address = address
      .trim()
      .split(" ")
      .join("%20");

    let URL = "some long URL"

    await request(URL, function(err, res) {
      if (err) {
        console.log(err);
      } else {
        let body = JSON.parse(res.body);
        callback(body);
      }
    });
  }

But this is my output... 但这是我的输出...

test
body

The "test" output should come after the body output. “测试”输出应在正文输出之后。

Question: What's going on here? 问题:这是怎么回事? To the best of my knowledge I think I did all the async/awaits correctly seeing as I'm not getting an promise errors. 据我所知,我认为我没有正确地执行所有异步/唤醒操作,因为我没有收到承诺错误。 Any ideas? 有任何想法吗?

The problem is that you basically await nothing in your parseGoogleCiv function. 问题在于您基本上不等待parseGoogleCiv函数中的任何事情。 May do: 可以做:

parseGoogleCiv: async (address) => {
  address = address
  .trim()
  .split(" ")
  .join("%20");

  let URL = "some long URL"

  try {
    return JSON.parse(
     (await new Promise((resolve,rej) =>  request(URL, function(err, res) { 
       if(err) return rej(err);
       resolve(res);
      }))).body
    );
  } catch(err){
    console.log(err);
  }
}

This is probably more elegant if you use the promisified request version : 如果使用承诺的请求版本,这可能会更优雅:

parseGoogleCiv(address){
  address = address
  .trim()
  .split(" ")
  .join("%20");

 const url = "someurl";

 return request(url)
   .then(res => JSON.parse( res.body ))
   .catch( err => console.log(err));
}

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

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