在 Javascript/Node.JS 中调用匿名函数时的堆栈顺序 [英] Stack order when calling anonymous functions in Javascript/Node.JS

查看:23
本文介绍了在 Javascript/Node.JS 中调用匿名函数时的堆栈顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用匿名函数时,javascript 中的堆栈顺序如何工作?我希望打印以下代码:第一次呼叫第二次呼叫第三次呼叫",但它打印:第二次呼叫第三次呼叫第一次呼叫".

How does stack order work in javascript when using anonymous functions? I would expect the following code to print: "first call second call third call", but instead it prints: "second call third call first call".

function findTweets(params, num)
{
     params = {
        q: params, 
        count: num ,
        language: 'en' 
     }
     T.get('search/tweets', params, function(err, data, response) {
         console.log("first call");
        });

     console.log("second call");
}
findTweets("a str",1)
console.log("third call");

任何帮助将不胜感激.谢谢

Any help would be greatly appreciated. Thanks

推荐答案

dmfay 是正确的,异步 T.get() 函数正在绊倒你.

dmfay is correct that the asynchronous T.get() function is tripping you up.

查看 MDN 关于并发模型的文章

JavaScript 从一个事件循环中运行,在该循环中处理来自队列的消息.每条消息都与一个功能相关联.当堆栈有容量时,从队列中拉出一条消息并进行处理.

JavaScript runs from an event loop where messages are processed from a queue. Each message is associated with a function. When the stack has capacity, a message is pulled from the queue and processed.

每条消息都被处理到完成,消息可以通过函数添加到队列中,包括将像你的 T.get() 函数一样异步处理的函数.在这种情况下,如果没有其他消息,则立即处理 T.get(),但如果有其他消息,例如 console.log('third call'),则 T.get() 必须等待插入它的消息进入堆栈,它必须等待它的回调完成才能调用 console.log().

Every message is processed to completion, and messages can be added to the queue by functions, including functions that will be processed asynchronously like your T.get() function. In this case, if there are no other messages, T.get() is processed right away, but if there are other messages such as console.log('third call'), T.get() has to wait to insert it's message into the the stack, and it has to wait for it's callbacks to complete before it can invoke console.log().

function findTweets(params, num)
{
     params = {
        q: params, 
        count: num ,
        language: 'en' 
     }
     T.get('search/tweets', params, function(err, data, response) {
         console.log("first call"); // 3. Ok, I'm done!
        });

     console.log("second call"); // 4. Finally!
}
findTweets("a str",1) //1. I can start now but can't finish until my callbacks do
console.log("third call"); // 2. Sweet! I can go right now.

如何让这些按照预期的顺序执行?尝试承诺和回调.

How can you get these to execute in the order you expect? Try a promise and a callback.

为了看到这一点,我用一个包含 get() 方法的对象存根了 twitterAPI 函数.存根 get() 方法使用 setTimeout() 欺骗延迟响应

In order to see this in action, I stubbed the twitterAPI function with an object that contains the get() method. The stubbed get() method spoofs a delayed response using setTimeout()

var twitterAPI = function () {
  this.get = function (method, params, callback) {
    setTimeout(function () {
      callback()
    }, 1000)
  }
}

var T = new twitterAPI()

function findTweets (params, num, callback) {
  params = {
    q: params,
    count: num,
    language: 'en'
  }

  var p1 = new Promise(function(resolve, reject) {
    T.get('search/tweets', params, function (err, data, response) {
      resolve("first call") // first call resolved as a promise
    })
  })

  p1.then(function(res) {
    console.log(res) // log resolved promise
    console.log("second call") // make second call
    return callback() // return callback so third call can go
  })
}

findTweets("a str", 1, function () {
  console.log("third call") // Finally, third call is called
})

/*
first call
second call
third call
*/

这篇关于在 Javascript/Node.JS 中调用匿名函数时的堆栈顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆