簡體   English   中英

使 return 語句等待,直到函數中的其他所有內容完成

[英]Make the return statement wait until everything else in the function is finished

我正在嘗試創建一個返回 SOAP 調用結果的函數(將npm-soap與 node.js 結合使用)。 問題是函數返回undefined是因為當到達 return 語句時 SOAP 調用還沒有完成。

我嘗試將 return 語句放在 SOAP 調用回調本身中,但隨后它返回 undefined。 我認為這是因為 return 語句應該在外部函數而不是內部函數中,就像我在下面的示例中所做的那樣。 SOAP 調用回調中的 console.log() 輸出正確的數據,所以我知道它就在那里。

如何使 return 語句等待內部 SOAP 調用? 謝謝!

var config = require('./config.js');
var soap = require('soap');

function getInvoices() {

    let invoices;

    // Connect to M1
    soap.createClient(config.endpoint, function(err, client) {

        // Log in
        client.login(
            { 
                username: config.username,
                apiKey: config.password
            }, 
            function(err, loginResult) {

            // Get invoices
            client.salesOrderInvoiceList(
                { 
                    sessionId: loginResult.loginReturn.$value
                }, 
                function(err, invoiceResult) {

                    // Save invoices
                    invoices = invoiceResult;
                    console.log(invoices); // <- Returns the right data

                    // Log out
                    client.endSession(
                        { 
                            sessionId: loginResult.loginReturn.$value
                        },
                        function(err, logoutResult) {
                        }
                    );

                }
            );

        });

    });

    // Return invoices
    return invoices; // <- Returns undefined

}

console.log(getInvoices(); // <- So this returns undefined as well

getInvoices返回一個Promise ,一旦所有回調完成,您就可以解決它,即

function getInvoices() {
  return new Promise((resolve, reject) => {
    // Connect to M1
    soap.createClient(config.endpoint, (err, client) => {
      if (err) return reject(err);

      // Log in
      client.login({ 
        username: config.username,
        apiKey: config.password
      }, (err, loginResult) => {
        if (err) return reject(err);

        // Get invoices
        client.salesOrderInvoiceList({ 
          sessionId: loginResult.loginReturn.$value
        }, (err, invoiceResult) => {
           if (err) return reject(err);

           // Log out & resolve the Promise
           client.endSession({ 
             sessionId: loginResult.loginReturn.$value
           }, (err, logoutResult) => 
             err ? reject(err) : resolve(invoiceResult)
           );
        });
    });
  });
}
...
(async () => {
  try {
    const invoices = await getInvoices();
    console.log(invoices);
  } catch (e) {
    console.error(e);
  }
})();

暫無
暫無

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

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