簡體   English   中英

等待函數返回,然后再移至下一行

[英]Waiting for a function to return before moving to the next line

我正在嘗試開發一種具有以下功能的方法:-調用返回類對象的函數-將這個對象推入數組-打印新數組

返回類對象的函數使用exec()函數來使用命令行執行腳本。 這可能需要花費幾秒鍾才能完成。

SampleFunction(data) {

    const xyzObject = xyz.otherfunction(data); 
    //other function takes a number of seconds to finish

    this.array.push(xyzObject); // Push object onto the array
    console.log(array);
    return xyzObject;
}

在我的代碼中,甚至在返回對象之前,將數組打印到控制台。 我怎樣才能解決這個問題?

理想情況下:重新組織代碼,以便正確處理exec是異步操作這一事實。 例如,您的函數可以接受回調或返回承諾,而不是直接返回結果。

在大多數情況下,一個非常第二最佳答案:你可以使用execSync

我建議您閱讀有關此主題的博客文章。

基本上,您需要將調用轉換為Promise,然后在等待命令完成時使用async / await運算符暫停線程。

遵循以下思路可以完成這項工作:

 // const { exec, execFile } = require('child_process'); const xyz = { otherfunction: data => { return new Promise((resolve, reject) => { // you do your exec() here with something like that: // exec('<command>', (err, stdout, stderr) => { // execFile('<file>', (err, stdout, stderr) => { // if (err) { reject(err) } // resolve(stdout); // }); setTimeout(() => { resolve(data); }, 1000); }); } }; const SampleFunction = async function(data) { let array = []; const xyzObject = await xyz.otherfunction(data); //other function takes a number of seconds to finish array.push(xyzObject); // Push object onto the array console.log(array); return xyzObject; } SampleFunction([ {city: 'Los Angeles', state: 'CA', population: '4M'}, {city: 'New York City', state: 'NY', population: '8.4M'}, {city: 'Atlanta', state: 'GA', population: '0.5M'}, ]); 

如果您實際上正在執行腳本文件,建議您使用execFile

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM