简体   繁体   English

javascript函数调用时间

[英]javascript function call timing

I am trying to implement a for loop that iterates through a list and subsequently calls two functions, only if the first function results are found. 我试图实现一个for循环,该循环遍历列表,然后仅在找到第一个函数结果的情况下调用两个函数。

The issue is that the second function (search.similar) might be taking longer to fetch results. 问题在于第二个函数(search.like) 可能需要更长的时间来获取结果。

With the code below, when I run, all of the appropriate output from (search.locate) is correct, but only the last element's results from myList are stored from the (search.similar) function. 使用下面的代码,当我运行时,来自(search.locate)的所有适当输出都是正确的,但是只有来自mylist的最后一个元素的结果是通过(search.similar)函数存储的。

ie. 即。 all_results = [[cat_res1,mouse_res2],[dog_res1,mouse_res2],[mouse_res1,mouse_res2]]

How do I fix this to append the right results in the right order? 如何解决此问题,以正确的顺序附加正确的结果?

ie. 即。 all_results = [[cat_res1,cat_res2],[dog_res1,dog_res2],[mouse_res1,mouse_res2]]

var search = require('./search');
var myList = ['cat','dog','mouse'];
var all_results = [];
for (i=0; i<myList.length; i++){
  /* locate function*/
  search.locate(myList[i], function (err, searchResult){
    if (err){
      console.log("Error");
      return;
    }

    if (!searchResult){
      console.log("Cannot find it");
      return;
    }

    /*similarity function*/
    /* seems to take longer*/
    search.similar(myList[i], function (err, similarResult){
      if (err){
        return;
      }

      if (!similarResult){
        return;
      }

      var res1 = searchResult.data;
      var res2 = similarResult.data;
      /* append results to array*/
      all_results.push([res1,res2]);
    }
  });
}

Javascript can be thought of as asynchronous, in that the execution of particular functions do not necessarily happen synchronously, however "describing JavaScript as asynchronous is perhaps misleading. It's more accurate to say that JavaScript is synchronous and single-threaded with various callback mechanisms" 可以将Javascript视为异步的,因为特定功能的执行不一定是同步发生的,但是“将JavaScript描述为异步可能会产生误导。更准确地说,JavaScript是同步的并且具有各种回调机制的单线程”

In order to accomplish your goal, though you may still get some ordering issues with the top array, you will need to wrap your .similar() call in another function that takes both arguments. 为了实现您的目标,尽管您可能仍然会遇到top数组的一些排序问题,但是您需要将.similar()调用包装在另一个接受两个参数的函数中。 Your reference to the "item" on the top search is changing: 您对顶部搜索中的“项目”的引用正在更改:

function searchNestedSimilar(item, topRes) {
    search.similar(item, function (err, similarResult) {

        if (err){
            return;
        }
        if (!topRes){
            return;
        }

        var res1 = topRes.data
        var res2 = similarResult.data

        // append results to array
        all_results.push([res1,res2])

    }
} 

function searchLocate(item) {
   search.locate(item, function (err, searchResult) {

    if (err){
        console.log("Error");
        return;
    }
    if (!searchResult){
        console.log("Cannot find it");
        return;
    }
    searchNestedSimilar(item, searchResults);
}

I encapsulated both calls to keep it modular, but since "item" is in the closure, you really only need the searchLocate() function to wrap your capture your item reference during iteration. 我封装了这两个调用以使其保持模块化,但是由于“ item”在闭包中,因此您实际上只需要searchLocate()函数在迭代期间包装捕获您的项目引用。

This is a good case for Promises (see Bluebird JS for example http://bluebirdjs.com/docs/getting-started.html ) or you could do it with async.map(). 这对于Promises是一个很好的案例(例如,请参阅Bluebird JS,例如http://bluebirdjs.com/docs/getting-started.html ),也可以使用async.map()做到这一点。

This page talks about it well, too. 此页面也很好地讨论了这一点。 http://promise-nuggets.github.io/articles/14-map-in-parallel.html http://promise-nuggets.github.io/articles/14-map-in-parallel.html

There are many Stack Overflows discussing Promises as well. 也有许多堆栈溢出讨论了Promises。 Understanding JS Promises for example. 例如, 了解JS Promises

A rough example of how to write this with a Promise: 一个如何用Promise编写一个粗略的例子:

var search = require('./search');
var myList = ['cat','dog','mouse']
var all_results = []
var Promise = require('bluebird');
var locate = Promise.promisify(search.locate);
var similar = Promise.promisify(search.similar);

for (i = 0; i < myList.length; i++){
    // locate function
    locate(myList[i], function (err, searchResult) {
        if (err) {
            console.log("Error");
            return;
        }
        if (!searchResult){
            console.log("Cannot find it");
            return;
        }
    }).then(function(result) {
        //similarity function
        similar(myList[i], function (err, similarResult) {
            if (err){
                return;
            }
            if (!similarResult){
                return;
            }

            var res1 = searchResult.data
            var res2 = similarResult.data

            // append results to array
            all_results.push([res1,res2])
        }).finally(function() {
            // NOP
        });
    });
}

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

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