【问题标题】:How to make sure that a JS function is finished running before executing the next callback function with own setTimeOut?在使用自己的 setTimeOut 执行下一个回调函数之前,如何确保 JS 函数完成运行?
【发布时间】:2018-01-13 01:25:45
【问题描述】:

我有多个具有自己的 setTimeOut 值的回调函数。当我尝试依次运行时,具有最短 setTimeOut 值的那个会首先呈现,即使它被称为最新的也是如此。

有类似的问题(如thisthisthis),但当每个函数都有自己的内部 setTimeout 值时,它们的答案就不起作用。

什么是最好的方法(使用纯 JS)强制函数等待(或确保前一个完成运行)直到前一个完成,而不使用额外的 setTimeOut?

代码:

function NumSequences(){};

NumSequences.prototype.one = function one(callback) {
 setTimeout(function() {
   callback()
   console.log('one');
 }, 1000);
};

NumSequences.prototype.two = function two(callback) {
 setTimeout(function() {
   callback()
   console.log('two');
 }, 500);
};

NumSequences.prototype.three = function three(callback) {
 setTimeout(function() {
   callback()
   console.log('three');
 }, 200);
};
var numSequences = new NumSequences();

function countNow(){};

var promise = new Promise(function(resolve) {
   resolve(numSequences.one(countNow));
});

promise.then(function() {
  return numSequences.two(countNow);
}).then(function() {
  return numSequences.three(countNow); 
});

结果:

three //coming first because the function three has the shortest setTimeout value
two 
one //coming at last despite being called first

结果应该是:

one
two 
three

链接到JSBin

【问题讨论】:

    标签: javascript promise synchronous


    【解决方案1】:

    为过程的每个部分定义函数,使用复制的数组数组作为函数调用的参数,移动数组直到数组中没有元素

    function NumSequences(message, time) {
      return new Promise(function(resolve) {
        setTimeout(function() {
          resolve(message)
        }, time)
      })
    }
    
    function count(value) {
      console.log(value);
    }
    
    function next(array) {
      if (array.length) {
        return process(array)
      } else {
        return "done"
      }
    }
    
    let arr = [
      ["one", 1000],
      ["two", 500],
      ["three", 200]
    ];
    
    let copy = arr.slice(0);
    
    function process(array) {
      return NumSequences.apply(null, array.shift())
        .then(count)
        .then(next.bind(null, array))
    }
    
    process(copy)
    .then(function(complete) {
      console.log(complete)
    })

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-22
      • 1970-01-01
      • 2020-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 2023-03-22
      相关资源
      最近更新 更多