提问者:小点点

对象不是在函数外部返回值,而是在函数内部返回值


getblog()从数据库中提取博客。

let getBlog = () => {
  let blogContent = {};

  let command = "select * from informations;";
  database.query(command, (err, results) => {
    if (err) console.log(err);

    for (let totalResults = 0; totalResults < results.length; totalResults++) {
      let newObjectForSending = {
        id: results[totalResults].id,
        title: results[totalResults].title,
        description: results[totalResults].description,
        likes: results[totalResults].likes,
      };
      blogContent[totalResults] = newObjectForSending;
    }
    console.log(blogContent);
    /*
here blogContent shows
{
"id":1,
"title":"this is title",
"description":"This is best description",
likes:"300"
}
*/
  });
  console.log(blogContent);
  /*
here blogContent shows
{ }
*/
  return blogContent;
};

为什么这里的blogContent在函数的上下文中是全局的,而我们正在内部更改它,所以它应该返回值,有人能解释为什么会这样吗?

有没有不使用promise/async/await的方法>>>有人给了我答案
我如何从异步调用返回响应?
但这一点我不知道,最主要的是我不知道Ajax。


共1个答案

匿名用户

首先,让我们创建一个异步执行程序

// It take 2 args, 1st is time in milliseconds, 2nd is callback function which return "Results"
function delayCallback(ms, fn) {
    setTimeout(fn, ms, "Results");
}

delaycallback是通过事件循环执行I/O,这意味着执行需要时间...

null

function delayCallback(time, fn) {
    setTimeout(fn, time, "Results");
}

console.log("Executing callback");
console.time("Callback executed...");
delayCallback(1000, () => {
    console.timeEnd("Callback executed...");
});

console.log("Hello World");