【问题标题】:Wait for two async functions to finish then continue in Node.js等待两个异步函数完成,然后在 Node.js 中继续
【发布时间】:2019-11-24 00:04:04
【问题描述】:

我正在使用 Node.js 开发一个应用程序,在该应用程序中我调用了两次异步函数,并将值分配给一个全局变量。

问题是我想使用这两个调用的结果来做其他事情,但是这个其他事情不会等待结果被分配。

这是我的代码:

var a;
var b;

let x = 'abcd';
foo(x).then(data=>{
    a = data;
});

x = 'efgh';
foo(x).then(data=>{
    b = data;
});

console.log(a + b); // for example

在执行a + b之前如何等待这两个函数完成?

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    您可以在这里使用Promise.all,等待两个promise,然后使用它们的数据:

    let promises = [];
    let x = 'abcd';
    promises.push(foo(x))
    
    x = 'efgh';
    promises.push(foo(x))
    
    Promise.all(promises).then(([a, b]) => {
      console.log(a, b); // for example
    });
    
    
    function foo(d) {
      return Promise.resolve({somePaddingData:"", d});
    }

    【讨论】:

      【解决方案2】:

      由于 foo 返回一个 Promise,您应该使用 async 关键字将您的函数标记为异步,并等待 foo 函数以 await 关键字响应。

       async function someFunction(){   
        let x = 'abcd';
        let a = await  foo(x);
      
        x = 'efgh';
        let b = await foo(x);
        console.log(a + b)
      }
      

      【讨论】:

      • 为什么混合使用 var 和 let ?
      • 我在async someFunction(){ 中收到SyntaxError: Unexpected identifier
      【解决方案3】:

      您可以使用await,而不是使用.then()。 所以这个:

      foo(x).then(data=>{
          a = data;
      });
      

      会是这样的:

      a = await foo(x);
      

      其他功能也是如此。这将导致您的执行等待函数返回。 但是请注意,为了使用await,您必须将使用它的语句,甚至更好的是整个块包装在一个声明为aync的函数中。您可以找到更多关于如何使用async here.

      【讨论】:

        【解决方案4】:

        试试这个:

        //using setInterval to wait for completion
        
        //a function which returns a callback
        function foo(x,callback){
          //do some computaion on x
          callback(x);
        };
        
        //to store the response
        let result = [];
        
        //calling foo method twice parallely
        foo("123",(data)=>{
          result.push(data);
        });
        
        foo("456",(data)=>{
          result.push(data);
        });
        
        //waiting till the above functions are done with the execution
        //setInterval function will check every 100 ms(can be any value) if the length of the result array is 2
        let timer = setInterval(() => {
          if (result.length == 2) {
            clearInterval(timer);
            //prints the two value
            console.log(result.join(""))
          }
        }, 100);

        【讨论】:

          猜你喜欢
          • 2016-10-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-06
          • 1970-01-01
          • 2018-11-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多