这是我遇到的一个问题,如果我没有在asyncCall函数中设置超时,那么响应将在异步代码完成之前发送,因此我无法从onlineBooksImages()获取图像
功能,但在以下代码中包含超时

  setTimeout(() => {


    if (onlineBook) {

        res.status(200).render("showBooks",
            {
                result: result,
                favourites: favourites,
                user: user,
                book: onlineBook

            });
    }



}, 5000);


延迟了发送响应的时间,因此我得到了图像,我该如何编写下面的代码,以消除超时,该超时比使用异步代码进行更快的加载要长

var boos = []
var boos2 = []
var boos3 = []
var foo = {}
var foo2 = {}
var foo3 = {}

const onlineBook= await Books2.findById(req.params.id);
const Ebook = await Ebooks.findById(req.params.id);

 function onlineBooksImages() {
    return new Promise(resolve => {
        setTimeout(() => {

            let temporaryVar = []
            onlineBook.allimages.forEach(element => {
                gfs.files.findOne({ _id: element }, (err, file) => {
                    if (!file || file.length === 0) {
                        return res.status(404).json({
                            err: "No file exist"
                        });
                    }
                    var u = []
                    u.push(onlineBook._id)
                    var img = []
                    img.push(file)
                    user.push(file)
                    foo3[u] = temporaryVar;
                    //console.log(user.length);
                });
            });
            boos3.push(foo3)

            resolve(boos3);
        }, 100);
    });
}
  async function asyncCall() {
    console.log('calling');
    if (onlineBook) {
        var result = await onlineBooksImages();
    } else if (Ebook) {
        var result2 = await someOtherFunction();//notImportant

    } else {
        return res.status(404).render('error', { user });
    }
    setTimeout(() => {


        if (onlineBook) {

            res.status(200).render("showBooks",
                {
                    result: result,
                    favourites: favourites,
                    user: user,
                    book: onlineBook

                });
        }



    }, 5000);

}

最佳答案

在回答之前...这里有一些有趣的代码

  this code looks wrong on many levels

  var u = [];
  u.push(onlineBook._id);
  // snip
  foo3[u] = temporaryVar;


现在,让我们说onlineBook._id === "abc"

因此u === ['abc']

所以foo3[u]foo3[u.toString()]相同...就是foo3['abc']

那么为什么不只是foo3[onlineBook._id] = temporaryVar;

但是即使看起来很奇怪,因为foo3中的每个属性都将引用同一数组

例如如果书号是'abc','def'和'ghi',则foo3.abcfoo3.deffoo3.ghi将是完全相同的空数组!

不管怎样,尽管我仍然对您的“全局” boos *和foo *变量感到困惑-但让我们解决一下您遇到的问题:

function async onlineBooksImages() {
  let temporaryVar = [];
  for (let element of onlineBook.allimages) {
    try {
      const file = await new Promise((resolve, reject) => {
        gfs.files.findOne({_id: element}, (err, file) => {
            if (err) {
                return reject(err);
            }
            temporaryVar.push(file);
            resolve(file);
        })
      });
      if (!file || file.length === 0) {
        return reject();
      }
      foo3[onlineBook._id] = temporaryVar;

    } catch(e) {
        // do nothing but catch the error
    }
  }
  if (Object.keys(foo3).length) {
    boos3.push(foo3);
    return boos3;
  } else {
    // reject if there were no images in any of allimages
    throw({status: 400, err: "No file exist"});
  }
}

async function asyncCall() {
  console.log('calling');
  try {
    if (onlineBook) {
      var result = await onlineBooksImages();
    } else if (Ebook) {
      var result2 = await someOtherFunction();//notImportant
    } else {
      return res.status(404).render('error', { user });
    }
    if (onlineBook) {
      res.status(200).render("showBooks", {
        result: result,
        favourites: favourites,
        user: user,
        book: onlineBook
      });
    }
  } catch(e) {
      if (e.status && e.err) {
        res.status(e.status).json({
          err: e.err
        });
      }
  }
}

07-25 20:54