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

查看:133
本文介绍了在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.

如何使它们按您期望的顺序执行?尝试一个Promise和一个回调.

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

为了了解这一点,我在twitterAPI函数中添加了一个包含get()方法的对象.残缺的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天全站免登陆