簡體   English   中英

方法不等待Promise被解析

[英]Method does not wait for Promise to be resolved

我有一個 function 我正在嘗試調用它,並且基本上強制它等待響應,然后再繼續下一件事。

我有兩個函數,都是異步的。

第一個看起來像這樣,所有以“_”開頭的參數都用作回調:

async function formatJson(input, _sendToThirdParty, _handleLogs, _setDimensions)
{
     ...do some work here to format the payload
     if(onlineConnectionRequired)
    {
         _setDimensions(itemToUpdate, object);
    }
    else {
         // Do non-online based transformations here
    }
    ...do more work after the above
}

基本上,我試圖調用這個方法 setDimensions ,它看起來像這樣:

async function setDimensions(itemToUpdate, object) {
    try
    {
        if(itemToUpdate != null)
        {
            console.log("Loading dimensions");
    
            await Promise.resolve(function() {
                ns.get(`inventoryItem/${object['Item ID']}?expandSubResources=true`)
                .then((res) => {
                    console.log("Inventory Item Loaded. Updating dimensions...");

                    itemToUpdate.consignments.push(
                        {
                            consignmentID: object.conID,
                            barcode: object.barcode,
                            itemID: '', // leaving as empty for now
                            width : res.data.custitem_width,
                            length : res.data.custitem_length,
                            height : res.data.custitem_height,
                            weight : res.data.custitem_weight,
                            fragile: object.fragile === 'T' ? 1 : 0,
                            description: object.description
                        }
                    );

                    console.log("Dimensions Finalised");
                })
            });
        }
    }
    catch(err)
    {
        console.log(err);
        const message = `Error attempting to set the dimensions for ${object['Item ID']}`;
        console.log(message);
        throw new Error(message);
    }
}

我遇到的問題是:

  1. 第一種方法中的代碼在等待 promise 解決之前繼續執行,但我需要它等待,以便我可以在它繼續執行下一個位之前完全構建有效負載
  2. 如果我嘗試在第一種方法中調用_setDimensions(...)之前包含await關鍵字,我會收到錯誤"SyntaxError: await is only valid in async function" ,但我會認為它異步的function?

如果有人可以提供幫助,那將非常感激! 謝謝!!

您的功能的正確設計如下:

formatJson(input, (err, value) => {
    if(err) {
        // Error handler goes here
        //console.log(err);
        throw err;
    } else {
        // Implementation for working with returned value
        console.log(value);
    }
});

function formatJson(input, callback)
{
    //...do some work here to format the payload
    if(onlineConnectionRequired)
    {

        setDimensions(itemToUpdate, object)
            .then((updatedItem) => {
                // Implement anything here to work with your
                // result coming from setDimensions() function

                //console.log(updatedItem);

                // Callback with null error and updatedItem as value
                callback(null, updatedItem);
            })
            .catch((err) => {
                // Callback with err object and null value
                callback(err, null);
            });
    }
    else {
         // Do non-online based transformations here
    }
    //...do more work after the above
}

function setDimensions(itemToUpdate, object) {
    try
    {
        if(inventoryItemID != null)
        {
            console.log("Loading dimensions");
    
            return new Promise(function(resolve, reject) {
                ns.get(`inventoryItem/${object['Item ID']}?expandSubResources=true`)
                    .then((res) => {
                        console.log("Inventory Item Loaded. Updating dimensions...");

                        itemToUpdate.consignments.push(
                            {
                                consignmentID: object.conID,
                                barcode: object.barcode,
                                itemID: '', // leaving as empty for now
                                width : res.data.custitem_width,
                                length : res.data.custitem_length,
                                height : res.data.custitem_height,
                                weight : res.data.custitem_weight,
                                fragile: object.fragile === 'T' ? 1 : 0,
                                description: object.description
                            }
                        );

                        console.log("Dimensions Finalised");

                        resolve(itemToUpdate);
                    })
                    .catch((err) => reject(err));
            });
        }
    }
    catch(err)
    {
        console.log(err);
        const message = `Error attempting to set the dimensions for ${object['Item ID']}`;
        console.log(message);
        throw new Error(message);
    }
}

您的代碼中的錯誤:

  1. 您的formatJson function 具有async關鍵字,但您的formatJson function 具有名為_sendToThirdParty, _handleLogs, _setDimensions的回調函數。 有 3 種類型的實現來創建異步代碼。 你可以使用回調、Promises 或 async/await。 但是 Promises 和 async/await 是相同的,除了它們的用例和語法。 當您將 function 定義為async fn() {...}時,它基本上會返回一個新的 Promise,因此等於說fn() { return new Promise(); } fn() { return new Promise(); } 帶有回調的函數的形狀類似於function(params, callback) { callback(cbParams); } 您可以在function(params, callback) { callback(cbParams); }的多個分支中使用調用回調 function。 但是你只有一個回調 function,你的代碼有 3 個回調函數。 另請注意,帶有回調的函數沒有async關鍵字。 這是無效的,因為正如我之前提到的,異步 function將返回 Promise。 因此,您不應該(但您可以)將 function 定義為async function(params, callback)就像您在第一種方法中所做的那樣。 這是定義沒有錯,它可以工作,但它是無效的。

  2. 您的第二種方法是異步 function 什么都不返回。 因此,我將其更改為正常的 function 並返回 Promise。

formatJson方法是否在異步方法中被調用? 它需要,並且在 _setDimensions 之前,您需要添加一個await關鍵字。 而且,正如丹尼爾所說,使用 promise 構造函數。

暫無
暫無

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

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